'How to store the result of ‘ls’ in a variable, and cd into that variable [duplicate]

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



Solution 1:[1]

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].

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jeff Schaller
Solution 2 perivesta