I want to make an script equivalent to zgrep or bzgrep, but using tar.

I made two very similar attempts and I would like to know if there is a better one and if they could be improved or they are gonna crash for some reason I can't see. I know how use tar and bzip2, but I use to have some troubles with shell expansion.

First using $@:

FILE_IN="${@: -1}"; ## Take last arg (file name) 
echo "FILE_IN: $FILE_IN"; 

INPUT_PARAMS="${@%%$FILE_IN}"; ## Take all args, but last (options and pattern)

### Here I have to treat $INPUT_FILE before using grep (skipped) ###  

exit $?; 

Second using variable (almost same above, just a couple of differences):

FILE_IN="${!ARGS[@]: -1}"; ## Take last arg (file name) 


### From here is identical 

They both seem to work, but then I took a look at script for bzgrep and it's much more complicated. So, it makes me think my scripts won't work.

Any thoughts? Can they be improved?


You need an array if you want to store more than one argument:

file_in="${@: -1}"


file_in="${@: -1}"
unset 'input_params[-1]'

Or, with just sh syntax:

for file_in do
  [ "$((n = n - 1))" -gt 0 ] || break
  set -- "$@" "$file_in"
# input_params in "$@"

(all uppercase variables should be reserved for environment variables).

  • A couple of comments: shift misses the contents of $@, right? I thought it was a bad practice, that's why I avoided and used ARGS variable. On the other hand, it makes any difference if you use an array or a just a string as I did to save all options? In such case, to use it would be: grep "$input_params" "$file_in"? Or "${![input_params[@]}? – Albert Dec 23 '14 at 12:14

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.