5

I have a shell skript:

#!/bin/bash
exec_command -k -q $1

for i in $@
do
  grep --color=always "$i" file
done

I call the script as

./grepskript -v searchstring1 searchstring2

I want to use the first argument for the exec_command and all other arguments for the do loop. How would I do this?

  • Can you edit your question? as is, you say ./grepskript -v searchstring1 searchstring2 : it seems grepskript is the name of the script itself, and that you intend in it to execute $1 (which is "-v" ?? is it really the executable name you want to execute?) and then do a loop grepping for "searchstring1" in the file, and then grepping "searchstring2" in the file, separately? – Olivier Dulac Mar 29 '18 at 14:25
  • @OlivierDulac the name of the script is grepskript. It does a calculation exec_command (with option -v). which outputs a file file from which I then grep seperately saerchstring1 and then searchstring2. – Fl.pf. Mar 29 '18 at 14:39
10

Use the shift command to push the positional arguments as you need. In your case, doing shift 1 would separate $1 (i.e. the first argument) from the rest of the args. Similarly shift 2 would shift first 2 arguments from the argument list and so on. And always remember to quote your variables/arguments to not let undergo word-splitting by the shell.

#!/bin/bash

exec_command -k -q "$1"
shift 1

for i in "$@"; do
  grep --color=always "$i" file
done

See the shift man page to understand more. This is a POSIX compliant option available across shells.

Or another way to do (bash specific) an index based expansion on the argument list $@ as below to start the loop from 2nd element on wards.

#!/bin/bash

exec_command -k -q "$1"

for i in "${@:2}"; do
  grep --color=always -- "$i" file
done

Also while iterating over the positional arguments in the first approach, you do just

for i; do
  grep --color=always -- "$i" file
done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.