-1

I would like to store the result of ls in a variable , then I want to cd into that variable.

I have script as follows.

Cd /home/dev/command
work_dir=$(ls -ltrd log$(date +%y%m%d)\* | tail -n 1)
echo $work_dir
cd “/home/dev/command/$work_dir”

It showing error like no such file or directory

How to CD into the directory which the ls command is showing

HatLess
  • 10,622
  • 5
  • 14
  • 32
Ananthu S
  • 3
  • 2
  • store the output of ls in variable a: `a=\`ls\`` then cd to this: `cd $a` – Exciter Apr 06 '22 at 10:15
  • work_dir=$(ls -ltrd log$(date +%y%m%d)* | tail -n 1). echo $work_dir cd “/home/dev/command/$work_dir”. That is what i am doing right? – Ananthu S Apr 06 '22 at 10:21
  • is the error something like `cd: drwxr-xr-x: No such file or directory`? What are you trying to do? `cd`ing in the last modified directory? – Fravadona Apr 06 '22 at 10:39
  • I am trying to do cd ing to the directory which this variable store $work_dir – Ananthu S Apr 06 '22 at 10:42

2 Answers2

1
cd “/home/dev/command/$work_dir”

You're using the unicode “ U+201C and ” U+201D left and right double quotation marks, which are used in english text instead of the plain " U+0022 quotation mark. So bash thinks the quotations are part of the directory name.

perivesta
  • 3,417
  • 1
  • 10
  • 25
0

Besides the unicode quotation marks mentioned in perivesta's answer, I'd also make some additional points:

  • you appear to have capitalized the cd command in Cd /home/dev/command. Perhaps you're using a Windows-based environment (cygwin or WSL?)
  • you escaped the * in ls -ltrd log$(date +%y%m%d)\*, which would be correct if your directory names actually ended in a literal asterisk, but an asterisk is often used as a wildcard to allow the substitution of any number of characters.
  • parsing the output of ls is hard to do correctly, and even harder if you're asking for ls -l output, as Fravadona hinted at in their comment!

Since you appear to want the most recent directory that matches a particular pattern, I would recommend using a UNIX shell that can sort by modification date natively, such as zsh.

$ zsh
$ cd /home/dev/command
$ cd log$(date +%y%m%d)*(om[1])

After changing to the right directory, this asks zsh to change to the directory that matches the wildcard log$(date +y%m%d)* sorted by modification date (newest first) with (om), picking the first (newest) item from that list with [1].

Jeff Schaller
  • 2,352
  • 5
  • 23
  • 38