I'm trying to make a bash script that will give me a command that will take a number n as argument and change the directory to the nth directory listed by running ls in the working directory. Here's what I have:
#! /bin/bash -
arg=$(ls --group-directories-first | awk -v first=$1 'NR == first' | tr -d '[[:space:]]')
cd $arg
It does not work. Nothing happens at all when I run it.
The first line does seem to be capturing the directory name in the way that I want. If I change the script to
#! /bin/bash -
arg=$(ls --group-directories-first | awk -v first=$1 'NR == first' | tr -d '[[:space:]]')
echo $arg
and run it in a directory in which the first directory is bin, the script outputs 'bin' when I give it the argument 1:
[user@manjaro ~]$ ls
bin/
Desktop/
Documents/
Downloads/
[user@manjaro ~]$ cdn 1
bin
So why does cd not take 'bin' and change to bin when I use the original version? And how should I change it?
One final note. When I try to do something similar outside a script it works fine:
[user@manjaro ~]$ foo=bin
[user@manjaro ~]$ cd $foo
[user@manjaro bin]$ pwd
/home/user/bin
Again, why?