How to get exact command line string from shell?

后端 未结 2 477
北荒
北荒 2021-01-13 04:01

I know about $*, $@, \"$@\" and even ${1+\"@\"} and what they mean.

I need to get access to the EXACT

相关标签:
2条回答
  • 2021-01-13 04:59

    In bash, you can get this from the shell history:

    set -o history
    shopt -s expand_aliases
    
    function myhack {
      line=$(history 1)
      line=${line#*[0-9]  }
      echo "You wrote: $line"
    }
    alias myhack='myhack #'
    

    Which works as you describe:

    $ myhack --args="stuff" * {1..10}    $PATH
    You wrote: myhack --args="stuff" * {1..10}    $PATH
    

    Also, here's a handy diagram:

    0 讨论(0)
  • 2021-01-13 05:03

    But I need to exactly reproduce a user-entered command line to be able to programmatically re-execute it in case of failure

    You don't need your exact command line for that; you can reconstruct an equivalent (even if not identical!) shell command yourself.

    #!/usr/bin/env bash
    printf -v cmd_q '%q ' "$@"
    echo "Executed with a command identical to: $cmd_q"
    

    ...though you don't even need that, because "$@" can be re-executed as-is, without knowing what the command that started it was:

    #!/usr/bin/env bash
    printf "Program is starting; received command line equivalent to: "
    printf '%q ' "$@"
    printf '\n'
    
    if [[ ! $already_restarted ]]; then
      echo "About to restart ourselves:
      exec "$@" # restart the program
    fi
    
    0 讨论(0)
提交回复
热议问题