Making bash script with command already containing '$1' -


somewhere found command sorts lines in input file number of characters(1st order) , alphabetically (2nd order):

while read -r l; echo "${#l} $l"; done < input.txt | sort -n | cut -d " " -f 2- > output.txt 

it works fine use command in bash script name of file sorted argument:

& cat numbersort.sh #!/bin/sh while read -r l; echo "${#l} $l"; done < $1 | sort -n | cut -d " " -f 2- > sorted-$1 

entering numbersort.sh input-txt doesn't give desired result, because $1 in using argument else.

how make command work in shell script?

there's nothing wrong original script when used simple arguments don't involve quoting issues. said, there few bugs addressed in below version:

#!/bin/bash while ifs= read -r line;   printf '%d %s\n' "${#line}" "$line" done <"$1" | sort -n | cut -d " " -f 2- >"sorted-$1" 
  • use #!/bin/bash if goal write bash script; #!/bin/sh shebang posix sh scripts, not bash.
  • clear ifs avoid pruning leading , trailing whitespace input , output lines
  • use printf rather echo avoid ambiguities in posix standard (see http://pubs.opengroup.org/onlinepubs/009604599/utilities/echo.html, particularly application usage , rationale sections).
  • quote expansions ("$1" rather $1) prevent them being word-split or glob-expanded

note creates new file rather operating in-place. if want operates in-place, tack && mv -- "sorted-$1" "$1" on end.


Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -