0

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.

2
  • I'm guessing you are doing this in your .bashrc? Aliases don't take arguments. Commented Jan 18, 2023 at 9:55
  • @suvayu Yes that is true. That was the one I have misfigured. Thanks! Commented Jan 18, 2023 at 10:35

1 Answer 1

3

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
~ $
Sign up to request clarification or add additional context in comments.

1 Comment

It works just as I expected! Many thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.