Escaping Strings in Bash

How to properly escape a string in bash from another script:

Full article: https://qntm.org/bash

Suppose you are writing a program, and you wish to call another program. However, the shell intermediates. In this case, you must quote and escape parameters to prevent malicious attacks that utilize the shell.

To escape a string for use as a command line argument in Bash, simply put a backslash in front of every non-alphanumeric character. Do not wrap the string in single quotes or double quotes.

Perl implementation

You can use the \Q and \E string modifiers.

my @args = ("ls", "-1", "foo.txt", "foo bar.txt");
my $cmd = join " ", map { "\Q$_\E"; } @args;
print "$cmd\n";

The original article uses the s// operator.

my @args = ("ls", "-1", "foo.txt", "foo bar.txt");
my $cmd = join " ", map { escape($_); } @args;
print "$cmd\n";

sub escape {
  my $arg = shift;
  $arg =~ s/([^a-zA-Z0-9])/\\$1/g;
  return $arg;
}

Tcl/Expect implementation

# Escape an arg for the shell.  See https://qntm.org/bash
proc esc {arg} {
    regsub -all {[^a-zA-Z0-9]} $arg {\\&}
}