0

I'm very interested in why this works this way and if we find a solution that's just a benefit of asking the question.

Using kshell,bash and observed the same results. Below is from GNU bash, version 5.1.16(1)-release (x86_64-pc-linux-gnu).

Below is from terminal.

alias tryme='tb=$1;cd $tb'
pwd
/home/tbink1
tryme /home/tbink1/Documents
pwd
/home/tbink1/Documents

But using below doesn't switch directories.

alias tryme='tb=$1;cd $tb;ls -latr'
pwd
/home/tbink1/Documents
tryme /home/tbink1/Pictures
<file list from /home/tbink1/Pictures>
pwd
/home/tbink1/Documents

Mystery to me why the second alias isn't changing directories. The second alias is what I would like to get working. Thanks for any help you give.

Progman
  • 16,827
  • 6
  • 33
  • 48
tbink1
  • 1
  • 1
  • `set /home/tbink1/Documents; tryme`. The behavior of `tryme` would be customized by setting `$1` before using the alias, not by providing an argument. – chepner Dec 23 '22 at 22:54

1 Answers1

2

Alias doesn't take arguments. It is replaced.

$ tryme /home/tbink1/Pictures
# tryme is _replaced_ by the alias, literally:
$ tb=$1;cd $tb;ls -latr /home/tbink1/Pictures
# then it's executed
# $1 is empty
+ tb=
# $tb is empty, 
+ cd
# and ls lists the directory
+ ls -latr /home/tbink1/Pictures

cd with no arguments changes to home directory. $1 is your shell $1, i.e. bash -s this_is_first_arg:

$ bash -s this_is_first_arg
$ echo $1
this_is_first_arg
$ alias tryme='tb=$1;cd $tb'
$ tryme
bash: cd: this_is_first_arg: No such file or directory

Use a function, not an alias.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111