In shell script how to print command to file and show the command as well?

35 Views Asked by At

I have multiple ls -l commands in my shell script and i want each line to append it's output to text file so i run it like this:

ls -l /directory/to/check/exists >> validation.log

The file will show only the output but I also want it to show the command that was executed. How can I have this without adding both command and echo of same command to avoid multiple lines?

Thank you

1

There are 1 best solutions below

0
yolenoyer On

You can use a bash function:

run() {
    echo "$@"
    "$@"
}

run ls -l /directory/to/check/exists >> validation.log

It has the advantage to let you format the command as you like, eg echo ">> $@".