bashfor-loopcommandzsh

How to run multiple commands in a for loop writhin in one line in zsh (or bash)


Let's say I want to run multiple command in a for loop writhin in one line in zsh (in that case, print the item name within a directory and print it

for i in *; echo "=================="; cat $i done;

with the given code, I get the proper number of "==================" printed but I only get the last item printed with the cat command


Solution

  • You can (almost) always just replace a newline with a semi-colon:

    for i in *; do echo "=================="; cat "$i"; done;
    

    Note that the trailing semi-colon (after "done") is not necessary.

    In the bash documentation, search for "control operator", and you will find:

    "A simple command is ... terminated by a control operator", which "is one of the following symbols: || & && ; ;; ( ) | <newline>"

    In other words, any of those symbols can be used to delimit commands, and the ; works just as well as a newline in most contexts.