3

I found a script which used this "trick" to achieve a toggle between running and printing commands:

echo_prefix="echo"
rm_cmd="rm file1 file2"
$echo_prefix $rm_cmd

This allows the user to dry run the script and then set echo_prefix="" to effectively run the script.

Still, I found many problems related to globbing and quoting so I was looking for a different and more robust approach.

2
  • Mm, what are the problems with globbing and quoting? Do you want to see e.g. globs and variables expanded in the output? (that's what the echo would do.)
    – ilkkachu
    Jan 12, 2018 at 14:50
  • Related to that, what should the "dry-run" mode do with command substitutions? They're commands in itself and might have effects, but they also affect the main command line, so should they be executed?
    – ilkkachu
    Jan 12, 2018 at 15:18

1 Answer 1

1

The best approach for this is using | bash.

So basically, you just echo your command. Here in my example rm file1 file2 and then | bash will run the output.

[ws] user ~ >echo "rm file1 file2"
rm file1 file2
[ws] user ~ >echo "rm file1 file2" | bash
rm: cannot remove ‘file1’: No such file or directory
rm: cannot remove ‘file2’: No such file or directory

@Kusalananda, If you have space in file name, you just have to adapt the first part to keep the quotes in the echo command:

echo "rm \"file with space\"" | bash
2
  • Try that with rm "file with space in name"...
    – Kusalananda
    Jan 12, 2018 at 13:15
  • You just have to adapt the first part: echo "rm \"file with space\"" | bash Jan 12, 2018 at 13:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .