Home > Software design >  bash: How to assign a directory name with spaces and single quotes to a variable
bash: How to assign a directory name with spaces and single quotes to a variable

Time:08-04

Here is an example directory

drwxr-xr-x 1 vangryman 197121 0 Jul 29 13:27 "2022-07-29 13.26.09 Very Angryman's Personal Meeting Room"/

So i'm trying to get the directory name to later cd into it

$ cat get_zoom.sh

#!/bin/bash

dir=$(ls -tr ../../Downloads/Documents/Zoom/ | tail -1)

cd "\"\"$dir\"\""

pwd

But no joy with how i wrap quotes

$ sh -x get_zoom.sh

   ls -tr ../../Downloads/Documents/Zoom/

   tail -1

  dir='2022-07-29 13.28.21 Very Angryman''\''s Personal Meeting Room'

  cd '""2022-07-29 13.28.21 Very Angryman'\''s Personal Meeting Room""'

get_zoom.sh: line 3: cd: ""2022-07-29 13.28.21 Very Angryman's Personal Meeting Room"": No such file or directory

CodePudding user response:

I don't see a problem with the assignment itself, unless you are using a very old version of the shell, in which case you sould have written

dir="$(.....)"

But your cd command is odd. It should be simple

cd "$dir"

CodePudding user response:

Since you are looking for the latest file, sort by reverse date, and pick the first item. Also, worth filter non-directories from being considered.

dir=$(ls -t ../../Downloads/Documents/Zoom/ | awk '/^d/ { print $1 ; exit }' )
cd "$dir"
  • Related