2

Executing and viewing bash command using the command line

I have a line of code that batch converts images but it doesn't show what image it's current operating on. Is there a way I can insert echo to show the command it's currently executing?

for i in *.jpg; do convert $i -filter Lanczos -resize 50% converted_$i.jpeg; done;

Example: After each line it I would like it to show the file it's converting img1.jpeg converted img2.jpeg converted

PS: I'm looking to run this from the command line. I don't want to create a separate file and run that.

Rick T
  • 2,223

1 Answers1

7

Background

In bash a for loop is used to assign a range(i.e. a list of items) within which a command(or a group of commands) is executed ... The range(AKA condition) is set within the first part of the for loop i.e. the part before the do(command grouping construct) e.g. for i in 1 2 3(will work in the range of 1-3 or on the elements in the list 1,2 and 3) ... The command(or the group of commands) is defined between the do and done command grouping constructs(these can be substituted in case of a for loop only with { and } in place of do and done respectively) AKA the body of the for loop.

When writing a for loop, every command/part of the loop(except the command grouping constructs) needs to terminate either with a new line or a semicolon e.g.:

for i in 1 2 3
    do
    echo "$i"
    done

or

for i in 1 2 3
    do echo "$i"
    done

or

for i in 1 2 3; do echo "$i"
    done

or

for i in 1 2 3; do echo "$i"; done

or with { ... } instead of do ... done command grouping constructs:

for i in 1 2 3; { echo "$i"; }

Notice that the usage of the undocumented { ... } command grouping constructs instead of the documented do ... done in a for loop in bash is not common(due to lack of proper documentation) and not advised(due to compatibility reasons and there is no guarantee it will still work in future versions of bash) ... I just included it to further illustrate the concept of the command grouping constructs.

Furthermore, in a for loop, if the range(i.e. in WORDS ... e.g. in 1 2 3) is not present, then in "$@"(i.e. the list of positional parameters) is assumed e.g.:

set -- 1 2 3; for i; do echo "$i"; done

Answer to your question

Is there a way I can insert echo to show the command it's currently executing?

Yes, you can do for ...; do command1; command2; command3; done like so:

for i in *.jpg; do echo "converting $i"; convert "$i" -filter Lanczos -resize 50% converted_$i.jpeg; [ "$?" -eq 0 ] && echo "$i converted"; done

Notice I added [ "$?" -eq 0 ] && echo "$i converted" which will check the exit status code of the previous command and echo "$i converted" will only be executed if the exit status code of the previous command was 0(i.e. success) which should mean that the image was successfully converted.

Raffa
  • 32,237