1

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
5
  • 3
    Simply quote "|ls" on the command line to prevent expansion (piping to ls) by the shell. E.g. bash yourscript "|ls" (single or double quotes are fine here) Commented Nov 7, 2021 at 3:20
  • 1
    If you invoke the script with quotes around the argument, as in script '|ls', it will work. If you don't use single or double quotes, then the command line is read as 'output of your script piped to ls', and ls doesn't read its standard input. So the problem is not inside the script — it is all in how you invoke it. Commented Nov 7, 2021 at 3:21
  • @DavidC.Rankin Is there any way to handle it in the script? Commented Nov 7, 2021 at 3:38
  • 1
    No. The expansion is preformed by the shell when your script is invoked. Meaning the shell would have already set up to pipe the result of your script to ls before the script was even started. By quoting the argument you tell the shell to treat it as a string (and argument to your script) and not further shell expressions. Commented Nov 7, 2021 at 3:52
  • oh. Now I got it. Thanks, @DavidC.Rankin. Commented Nov 7, 2021 at 3:59

1 Answer 1

1

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"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.