Home > Net >  Why my default variable is not working in bash script?
Why my default variable is not working in bash script?

Time:01-19

Here it is my script.

alias h='history "${1:-25}"'

My desirable result is when it gets variable like h 100 it shows the results of history 100 and no given inputs like h, it shows 25 elements like history 25.

But it works only when I hit h ,showing 25 results, other than that it gave me argument error.

-bash: history: too many arguments

I have tried ${1:-25} but it returns error either.

-bash: $1: cannot assign in this way

Sorry if it is duplicated, but bash script is quite tricky to look up since it has $ and numbers.

CodePudding user response:

An alias can't accept parameters. They take arguments only at the end, and they are not positional (not accessible as $1, $2, etc). It's equivalent to:

alias myAlias="command opt"
myAlias $@  
# Is the same as: command opt arg1 arg2 ...

You should use a bash function, one that will receive the param and call history:

function h() {
    x="${1:-25}"                       # Take arg $1, use 25 as fallback
    echo "Calling history with: $x"    # Log $x value as example
    history $x                         # Call history with $x
}

Usage:

~ $ h
Calling history with: 25
  448  xxx
  ...
  471  yyy
  472  zzz
~ $ h 1
Calling history with: 1
  473  h 1
~ $
  •  Tags:  
  • bash
  • Related