I am new to bash. Can someone please point me to the error in the code.
for x in `ls`;do `if(echo $x|grep "-2"); then rm $x; fi`; done;
I am basically trying to remove all the files ending with "-2.jpg"
I am new to bash. Can someone please point me to the error in the code.
for x in `ls`;do `if(echo $x|grep "-2"); then rm $x; fi`; done;
I am basically trying to remove all the files ending with "-2.jpg"
Don't use command substitution (backquotes) inside your for block. Command substitution is only used for getting the output to be used for assigning to a variable or for evaluating as another command.
`if(echo $x|grep "-2"); then echo 'yo'; fi`
You also need to add a space between if and the expression that follows it:
if (echo $x|grep "-2"); ...
Command substitution is also not necessary:
if echo $x | grep "-2"
You can also use -q to prevent messages being shown from grep:
if echo $x | grep -q "-2"
You also need to use -e to preven -2 from being interpretted as a wrong option to grep:
if echo $x | grep -q -e "-2"
Some of your variables should also be placed inside double quotes to prevent word splitting:
if echo "$x" | grep -q -e "-2"
Prefer $() over backticks when doing command substitution as well:
for x in $(ls);do ...
Finally the better form:
for x in $(ls); do if echo "$x" | grep -q -e "-2"; then echo 'yo'; fi; done
Better not get values through word splitting as it's also subject to pathname expansion and unexpected changes may occur. Use while read loop and process substitution instead. With ls, use -1 as well to show entries line by line:
while IFS= read -r x; do if echo "$x" | grep -q -e "-2"; then echo 'yo'; fi; done < <(ls -1)
When doing command substitution or process substitution, if the last command is a call to an external binary, add exec to prevent unnecessary fork:
$(exec ls -1)
<(exec ls -1)
You can also just use comparisons over using grep:
if [[ $x == *-2* ]]; then
You have to remove the backquotes for the do part, otherwise it means that you want to execute the filename. Also consider this alternative:
for x in `find -name "*-2.jpg"`; do echo $x; echo "yo"; done