简体   繁体   中英

Get full command from shell script

I'm looking for a way to access the full command from shell script, eg

Assume I have a script called test.sh . When I run it, the command line is passed to ruby as is (except the script itself is removed).

$ test.sh print ENV['HOME']

Is equivalent to

$ ruby -e "print ENV['HOME']"

When you run:

test.sh print ENV['HOME']

...then, before test.sh is started, the shell runs string-splitting, expansion, and similar processes. Thus, what's eventually run is (assuming no glob expansion):

execvp("test.sh", {"test.sh", "print", "ENV[HOME]"});

If you have a file named ENVH in the current directory, the shell may treat ENV['HOME'] as a glob, expanding it by replacing the glob expression with the filename, and thus running:

execvp("test.sh", {"test.sh", "print", "ENVH"});

...in any event, what exists on the other side of the execv* -series call done to run the new program has no information which was local to the original shell -- and thus no way of knowing what the original command was before parsing and expansion. Thus, it is impossible to retrieve the original string unless the outer shell is modified to expose it out-of-band (as via an environment variable).

This is why your calling convention should instead require:

test.sh "print ENV['HOME']"

or, allowing even more freedom from shell quoting/escaping syntax, passing program text via stdin, as with:

test.sh <<'EOF'
print ENV['HOME']
EOF

Now, if you want to modify your shell to do that, I'd suggest a function that exposes BASH_COMMAND . For instance:

shopt -s extdebug
expose_command() {
  export SHELL_COMMAND="$BASH_COMMAND"
  return 0
}
trap expose_command DEBUG

...then, inside test.sh , you can refer to SHELL_COMMAND . Again, however: This will only work if the calling shell had that trap configured, as within a user's ~/.bashrc ; you can't simply put the above content in a script and expect it to work, because it's only the interactive shell -- the script's parent process -- that has access to this information and is thus able to expose it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM