Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

echo that shell-escapes arguments [duplicate]

Is there a command that not just echos it's argument but also escapes them if needed (e.g. if a argument contains white space or a special character)?

I'd need it in some shell magic where instead of executing a command in one script I echo the command. This output gets piped to a python script that finally executes the commands in a more efficient manner (it loads the main() method of the actual target python script and executes it with the given arguments and an additional parameter by witch calculated data is cached between runs of main()).

Instead of that I could of course port all the shell magic to python where I wouldn't need to pipe anything.

like image 860
panzi Avatar asked Apr 28 '10 17:04

panzi


People also ask

What does echo $shell do in Linux?

The echo command is used to display a line of text that is passed in as an argument. This is a bash command that is mostly used in shell scripts to output status to the screen or to a file.

What is $@ in shell script?

$@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

How do you echo escape?

\e - Displays an escape character. \f - Displays a form feed character. \n - Displays a new line. \r - Displays a carriage return.

What is $* in Bash?

Number of arguments. $* All positional arguments (as a single word) $@ All positional arguments (as separate strings)


1 Answers

With bash, the printf builtin has an additional format specifier %q, which prints the corresponding argument in a friendly way:

In addition to the standard printf(1) formats, %b causes printf to expand backslash escape sequences in the corresponding argument (except that \c terminates output, backslashes in \', \", and \? are not removed, and octal escapes beginning with \0 may contain up to four digits), and %q causes printf to output the corresponding argument in a format that can be reused as shell input.

So you can do something like this:

printf %q "$VARIABLE"
printf %q "$(my_command)"

to get the contents of a variable or a command's output in a format which is safe to pass in as input again (i.e. spaces escaped). For example:

$ printf "%q\n" "foo bar"
foo\ bar

(I added a newline just so it'll be pretty in an interactive shell.)

like image 69
Cascabel Avatar answered Nov 15 '22 23:11

Cascabel