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

前端 未结 6 1505
走了就别回头了
走了就别回头了 2021-02-02 12:49

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? T

6条回答
  •  失恋的感觉
    2021-02-02 13:50

    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).

提交回复
热议问题