7

I would like to add an alias to a command in my .bashrc file, as in this example:

alias take_row="cat prova.csv_001.txt | awk -v nrow="${nrow}" '{if (NR==nrow) print}'"

But I would like to specify the nrow variable when I launch the command from the terminal. As an example:

take_row 1 --> the script takes the first row

take_row 20 --> the script takes the 20th row

How do I write inside the command something like <command> | <read nrow user input>, etc.?

12

Use a function instead of an alias, in which case you can refer to positional parameters such as $1, etc.

take_row () {
    local nrow=$1
    cat prova.csv_001.txt | awk -v nrow="${nrow}" '{if (NR==nrow) print}'
}

In this particular case, you can also address the useless use of cat:

take_row () {
    local nrow=$1
    awk -v nrow="${nrow}" '{if (NR==nrow) print}' prova.csv_001.txt
}
  • Better yet, use an external shell script kept, for example, in ~/bin. – jrw32982 Jan 30 at 19:28
  • 1
    @jrw32982 There are limitations to an external script, for example you can't change directories or modify the environment of the current shell, which an alias can do and so can a function... But if neither of these are needed, then yes an external script is a possibility. – filbranden Jan 30 at 21:41
  • 1
    My thesis is that unless there is a limitation which requires an alias or function due to some reason similar to those you suggest, then an external shell script should be preferred virtually always over an alias or a function defined by .bashrc. In the case at hand, there seems to be no reason which would prevent using an external script, and therefore, that is the preferred solution. – jrw32982 Jan 31 at 1:17
  • 1
    @jrw32982 If you think people should heed your advice it would help if you explain why. – B Layer Feb 18 at 12:44
  • @BLayer Basically, it's because external commands are the foundational unit. Why should every interactive shell load into memory and carry around a collection of aliases and functions which serve no purpose for that session? External commands are called into action on demand instead of being preloaded. External commands can be more easily tested, reloaded, etc. There are entire development cultures and environments for building and testing external commands and their components but nothing for aliases and functions. Ksh93 has FPATH to try to make functions more like commands. – jrw32982 Feb 18 at 16:41

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.