Home > Mobile >  passing command as argument in bash
passing command as argument in bash

Time:11-07

I have a simple script that takes the first argument from the command line and prints hello, first_arg.

But when I pass |ls, it is printing files in the current directory.

My script file

#! /bin/bash

echo "Hello, $1."

I tried multiple things

  • echo "Hello, '$'"
  • echo "Hello," "$1"
  • printf "Hello %s" "$1"

I want output like Hello, |ls

I checked quoting and this answer https://unix.stackexchange.com/questions/171346/security-implications-of-forgetting-to-quote-a-variable-in-bash-posix-shells

Edit

but It is not happening with input like

echo "input: "
read name
echo "Hello, $name."  # output Hello, |ls
echo "Hello, " $name  # output Hello, |ls

CodePudding user response:

You need to quote the pipe when invoking the script. Otherwise the shell will arrange for the standard output your script to be sent standard input of ls and you will end up with the output as if you hand run ls on it's own. Either of these would do:

./simple.sh \|ls
./simple.sh '|ls'
./simple.sh "|ls"
  •  Tags:  
  • bash
  • Related