I am iterating through a folder of files using bash, but I need to cut the preceding path. For instance if I have this ‘/temp/test/filename’ I want to cut off the ‘/temp/test/’ and store the file name to a variable so I can write a log with the filename in it.
Can anyone help me out? The problem is that the variable temp is always empty.
Here is my bash code:
#!/bin/bash
for file in /temp/test/*
do
if [[ ! -f "$file" ]]
then
continue
fi
temp="$file"|cut -d'/' -f3
$file > /var/log/$temp$(date +%Y%m%d%H%M%S).log
done
exit
Try that :
Another solution is to use
basename:The first solution is a parameter expansion and it’s a
bashbuiltin, so we increase performance.Your line
temp="$file"|cut -d'/' -f3is broken.var=$(command)STDINof the command with ahere-string(<<<) or withecho value | commandfinally, if you’d want to use
cut: