0

I'm trying to bypass arg to execute multiple commands with $addr in a shell script,but not worked.

#1.sh
arg='google.com |cat 1.txt'
echo ${arg}
addr="`echo ${arg}| sed 's|[\]||g' | sed 's|%20| |g'`"         
echo ${addr}                                       
addr="ping -c 1 "$addr
echo ${addr}                                                 
$addr
./1.sh                                                          
google.com |cat 1.txt
google.com |cat 1.txt
ping -c 1 google.com |cat 1.txt
ping: 1.txt: Name or service not known

In bash, It worked.

ping google.com|cat 1.txt
import java.lang.Runtime;
import java.lang.Process;
......

when arg='google.com -p 1', it worked.

arg='google.com -p 1'
echo ${arg}
addr="`echo ${arg}| sed 's|[\]||g' | sed 's|%20| |g'`"         
echo ${addr}                                       
addr="ping -c 1 "$addr
echo ${addr}                                                 
$addr

# ./1.sh
google.com -p 1
google.com -p 1
ping -c 1 google.com -p 1
PATTERN: 0x01
PING google.com(tsa01s13-in-x0e.1e100.net (2404:6800:4012:4::200e)) 56 data bytes

I think the problem is addr="ping -c 1 "$addr, What does "string"$arg exactly did, how to escape "string"$arg to excute command?

chanra
  • 1
  • 1
  • 1
    Using a command like `$addr` to invoke a pipeline is intrinsically, inherently broken. Don't ever store commands in strings; see [BashFAQ #50](https://mywiki.wooledge.org/BashFAQ/050). `addr="ping -c 1 "$addr` just prepends the string `ping -c 1` to the prior contents of `addr`; there's nothing wrong with it -- the problem is with the larger approach of using a string to store code in the first place. – Charles Duffy Aug 15 '23 at 21:32
  • 1
    Shell is more like a normal programming language than it might look. You know how in Python you can't put `cmd = 'for item in list:'` and then use `cmd` instead of a `for` loop without doing horrible things? POSIX-family shells are the same way; It may _look_ like it blurs the line between data and syntax, but that line is actually very solid and well-defined (which is good: otherwise it would be impossible to write secure code in shell scripts that handle untrusted data). – Charles Duffy Aug 15 '23 at 21:36
  • (in particular: unquoted expansions go through only two expansion steps, word-splitting and globbing; they skip anything that's really dangerous -- no command substitutions, no pipelines, no redirections, no quoting/unquoting characters processed as syntax rather than literal, etc; that's why only extremely simple commands look like they work when you run `$cmd`, and why your `|` is treated as an argument to `ping`, not a separator into multiple commands) – Charles Duffy Aug 15 '23 at 21:41

0 Answers0