I have a problem, I would like to pipe ls and cd together. I create shell pipe like:
cesta = ls -lat | awk 'NR==2 {print $8"/"}'
cd $cesta
But it doesn't work. Could you help me. And I didn't receive any error.
Filip
I have a problem, I would like to pipe ls and cd together. I create shell pipe like:
cesta = ls -lat | awk 'NR==2 {print $8"/"}'
cd $cesta
But it doesn't work. Could you help me. And I didn't receive any error.
Filip
There are a few issues with what you're attempting. First of all, to set a variable's value, you can't have spaces around the =
. Then, in order to capture the output of a command you need either backtics, or preferably $()
.
Finally, and most importantly, you should not parse ls
, it is very hard to do well and extremely prone to errors. Your approach will break if your directory name contains a space for example. In the examples below, what is the 8th
field?
$ ls -l
total 0
-rw-r--r-- 1 terdon terdon 0 Nov 11 14:59 file1
-rw-r--r-- 1 terdon terdon 0 Nov 11 2013 file2
-rw-r--r-- 1 terdon terdon 0 Nov 11 15:00 file 2
-----
|--------> 8th field
The file/directory name might be the 9th field, or it might be the 9th and 10th fields, or even more. Plus, the date format can change between locales. Basically, using ls
for this is a horrible idea. Instead, use stat
and sort by time:
$ cesta=$(stat --printf "%X %n
" * | sort -nk1,1 | cut -f 2- | awk 'NR==2')
$ cd "$cesta"