0

I have a bash script that takes multiple arguments and I want to log what command is used to run it. For example if the command looks like this:

bash my_script.sh -a 1 -b 2 -c 3

I want the script to write this exact line to a file like log.txt .

  • Can't be done; _no_ program knows the command line used to start it, or even if it _was_ started from a command line at all. – Charles Duffy Mar 22 '21 at 20:20
  • For example, `subprocess.Popen(['bash', 'my_script.sh', '-a', '1', '-b', '2', '-c', '3'])` in Python isn't a command-line string but an argv array. – Charles Duffy Mar 22 '21 at 20:21
  • ...UNIX processes are only given their array of arguments, not the string that array was generated from (if it was even generated from a string at all). – Charles Duffy Mar 22 '21 at 20:22
  • You can trivially generate an **equivalent** command line (one that, when run, would generate the same array of arguments the operating system passed you). You _can't_ reliably get the **exact** command line. – Charles Duffy Mar 22 '21 at 20:22
  • ...one cheap/easy way to get that equivalent command line: `printf '%q ' "$@"; echo` – Charles Duffy Mar 22 '21 at 20:23
  • https://stackoverflow.com/questions/3811345/how-to-pass-all-arguments-passed-to-my-bash-script-to-a-function-of-mine has a similar problem, something like `echo $0 $@` will do. – Kunal Nagpal Mar 22 '21 at 20:24
  • Similarly, `./myprogram "hello world" foo bar` generates _the exact same argument array_ as `./myprogram hello\ world foo bar` or `./myprogram hello' 'world foo bar`. The program being called can't tell the difference between them, because there _is_ no difference between them. – Charles Duffy Mar 22 '21 at 20:25
  • @KunalNagpal, ...that's a quite different question. The OP here isn't asking how to pass arguments through, they're asking how to log them. – Charles Duffy Mar 22 '21 at 20:25
  • @CharlesDuffy My bad, updated the comment for clarity. – Kunal Nagpal Mar 22 '21 at 20:28
  • @KunalNagpal Thanks, this works for me. I am parsing arguments with a case loop and shifts. Would it break argument parsing if I put `echo bash $0 $@ > log.txt` at the beginning of the script? – Saygın Güleç Mar 22 '21 at 20:59
  • @SaygınGüleç, you can do that but it isn't actually accurate. `echo bash $0 $@` logs the exact same thing for `yourscript one two three` and `yourscript "one two" three` and `yourscript "one two three"`, even though they're very different commands. There's a reason I suggested using `printf '%q ' "$@"` above. – Charles Duffy Mar 22 '21 at 21:53
  • ...Docker does that same class of thing (logging command lines without quoting or escaping to show where arguments begin and end), and it's a constant source of questions here from people misunderstanding those logs. – Charles Duffy Mar 22 '21 at 21:54

0 Answers0