58

I have this example shell script:

echo /$1/

So I may call

$ . ./script 5
# output: /5/

I want to pipe the script into sh(ell), but can I pass the arg too ?

cat script | sh 
# output: //
PeterMmm
  • 24,152
  • 13
  • 73
  • 111

3 Answers3

62

You can pass arguments to the shell using the -s option:

cat script | bash -s 5
Anton Kovalenko
  • 20,999
  • 2
  • 37
  • 69
  • 3
    Or preferably `bash -s 5 < script`, if `bash` really just needs to read a script from a file (and not a more complicated pipeline). – chepner Feb 04 '13 at 19:36
  • 1
    @chepner: If it were actually reading from a file and not a more complicated pipeline, then it would be better to do `(ba)sh script 5`. – Matt Feb 06 '15 at 17:28
  • 2
    not works for `-p` like (which starts from dash) `cat script | bash -s -a -b -c` see answer http://stackoverflow.com/a/25563308/983232 – x'ES Oct 09 '16 at 10:01
  • 3
    if I want to pass "-i" to my program, cat script | bash -s -i does not work!! -i is interpreted by bash! How? I tried escaping it but nothing. – Zibri Dec 13 '16 at 17:45
44

Use bash -s -- <args>

e.g, install google cloud sdk

~ curl https://sdk.cloud.google.com | bash -s -- --disable-prompts

northtree
  • 8,569
  • 11
  • 61
  • 80
15
cat script | sh -s -- 5

The -s argument tells sh to take commands from standard input and not to require a filename as a positional argument. (Otherwise, without -s, the next non-flag argument would be treated as a filename.)

The -- tells sh to stop processing further arguments so that they are only picked up by the script (rather than applying to sh itself). This is useful in situations where you need to pass a flag to your script that begins with - or -- (e.g.: --dry-run) that must be ignored by sh. Also note that a single - is equivalent to --.

cat script | sh -s - --dry-run
Wyck
  • 10,311
  • 6
  • 39
  • 60
  • Where is behavior like this documented? I tried `man sh` and `sh --help` on Mac – francojposa Aug 27 '21 at 17:47
  • @francojposa [Here's one place](https://www.unix.com/man-page/osx/1/sh/) although I usually just type `man sh` into Google. – Wyck Aug 27 '21 at 18:13