Sunday, May 12, 2024
4
rated 0 times [  4] [ 0]  / answers: 1 / hits: 402  / 2 Years ago, wed, february 9, 2022, 1:01:55

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


More From » command-line

 Answers
6

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"

[#22441] Thursday, February 10, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anatta

Total Points: 326
Total Questions: 128
Total Answers: 96

Location: Jordan
Member since Sun, Jun 26, 2022
2 Years ago
;