Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Echo command, and then run it? (Like make)

Is there some way to get bash into a sort of verbose mode where, such that, when it's running a shell script, it echoes out the command it's going to run before running it? That is, so that it's possible to see the commands that were run (as well as their output), similar to the output of make?

That is, if running a shell script like

echo "Hello, World"

I would like the following output

echo "Hello, World"
Hello, World

Alternatively, is it possible to write a bash function called echo_and_run that will output a command and then run it?

$ echo_and_run echo "Hello, World"
echo "Hello, World"
Hello, World
like image 488
mjs Avatar asked Sep 01 '12 22:09

mjs


People also ask

Does echo run the command?

Explanation: echo will print the command but not execute it. Just omit it to actually execute the command.

What does >> do for echo command?

1 Answer. >> redirects the output of the command on its left hand side to the end of the file on the right-hand side.

Which command is used instead of echo command?

Which command is used as an alternative to echo command? Explanation: printf command is available on most UNIX systems and it behaves much like a substitution for echo command. It supports many of the formats which are used by C's printf function.

How do you break a line in echo command?

There are a couple of different ways we can print a newline character. The most common way is to use the echo command. However, the printf command also works fine. Using the backslash character for newline “\n” is the conventional way.


2 Answers

You could make your own function to echo commands before calling eval.

Bash also has a debugging feature. Once you set -x bash will display each command before executing it.

cnicutar@shell:~/dir$ set -x
cnicutar@shell:~/dir$ ls
+ ls --color=auto
a  b  c  d  e  f
like image 148
cnicutar Avatar answered Oct 16 '22 12:10

cnicutar


To answer the second part of your question, here's a shell function that does what you want:

echo_and_run() { echo "$*" ; "$@" ; }

I use something similar to this:

echo_and_run() { echo "\$ $*" ; "$@" ; }

which prints $ in front of the command (it looks like a shell prompt and makes it clearer that it's a command). I sometimes use this in scripts when I want to show some (but not all) of the commands it's executing.

As others have mentioned, it does lose quotation marks:

$ echo_and_run echo "Hello, world"
$ echo Hello, world
Hello, world
$ 

but I don't think there's any good way to avoid that; the shell strips quotation marks before echo_and_run gets a chance to see them. You could write a script that would check for arguments containing spaces and other shell metacharacters and add quotation marks as needed (which still wouldn't necessarily match the quotation marks you actually typed).

like image 20
Keith Thompson Avatar answered Oct 16 '22 12:10

Keith Thompson