[bash] cd: too many arguments

Hello everyone,

Could someone please explain to me why I get cd: too many arguments when I select a dir that has one or more spaces in the name?

This is the code

#!/bin/bash

tmp_loc=$(zenity --file-selection --directory)
if [[ -z $tmp_loc && ${tmp_loc+x} ]]; then
  exit 0
else
  location=${tmp_loc// /\\ }  # this adds backslashes if need it
  echo $location                   
  cd $location      # cd: too many arguments if the dir's name has spaces
 fi

Thank you in advance.

Hi,

Try quoting your variables:

tmp_loc=$(zenity --file-selection --directory)
if [[ -z "$tmp_loc" && "${tmp_loc+x}" ]]; then
  exit 0
else
  location=${tmp_loc}  
  echo "$location"                  
  cd "$location"
fi              
1 Like

It seems to be working... I will try to do some tests and I will report back to you.

Hi, yes I removed the extra quote in my post...
Try adding

set -x

to your script to see what is going on and/or print the content (with quotes!) of the variables of every step.

I am not sure what you are trying to accomplish with

[[ -z "$tmp_loc" && "${tmp_loc+x}" ]]

I guess it is to test if the string is empty or unset..

Perhaps that should be something like this? :

[[ -z "$tmp_loc" ]]

Yes, you are right.

The below code is used to check if the string is empty

[[ -z "$tmp_loc" && "${tmp_loc+x}" ]]

I will do the suggested modification and I will let you know later today.

--- Post updated at 09:15 AM ---

I just tried and is not working...

What I need my script to do is to get the location from the user, move into it and perform some work.

The code you provided me works only with dirs that do not have spaces in their names.

I am going to bed now but I will keep you posted in case I find a solution.

Thank you again

You're welcome. Note that I had also modified this line:

location=${tmp_loc}

So if your old line is still there, perhaps that may be the problem?
(since you do not need to escape the spaces when you use proper quoting)...

The quoting should allow spaces in pathnames to work as intended..
Otherwise could you post your revised code?

Maybe I'm being a little dense, but why this?

if [[ -z "$tmp_loc" && "${tmp_loc+x}" ]]; then

It seems to me that the part in red is completely superfluous. In fact it will give a false result in the unlikely event that tmp_loc is unset (rather than set to null string).

Andrew

Hello apmcd47,
I was able to solve my issue thanks to your suggestion

1- I removed

location=${tmp_loc// /\\ }

2- I modified the

cd $location

with

cd "$location"

I guess last night I was too tired to understand it :stuck_out_tongue: