Search code examples
bashshellvariablescd

open directory with a variable bash shell


I'am reading in a variable that will contain a version of a certain file (Ex.: V1.0.10) by the following command.

read Version

and there is a possibility that that variable contains dots and I remove them by the next command:

New_Version=`echo $Version | sed -e 's/\.//g'`

but if I use this variable later on in the script, nothing changes at this variable, and I just use the cd command:

cd /data/group/$New_Version

or

cd /data/group/"$New_Version"

Then the error: No such file or directory... : line ...: cd:/data/group/V1010. I double checked, the files exists, the name is correct but he doesn't find or recognize the directory?

What am I doing wrong?

Hope someone can help!

Thanks


Solution

  • UPDATE: The OP says that the problem was a hidden character in his input. This answer does not describe how to solve that problem. Nonetheless, the OP has marked this answer as accepted. See the comments of Charles Duffy for the actual solution to the OP's problem.

    Caveat: I am taking everything in your problem description literally, which leads to the answer below. If you provide examples of the strings that will be passed through $Version it would help clarify the issue.


    As I understand it you're reading in the full path of a file in your variable with read Version. Now if you say echo $Version you should get /path/to/foo.bar.

    I don't think you'd want to cd into the file /path/to/foo.bar. You'll get an error: Not a directory, because it's a file, not a directory.

    Now, consider what sed -e /\.//g will do to the pathname.

    echo "/path/to/foo.bar" | sed -e '/\.//g'
    /path/to/foobar
    

    Does /path/to/foobar actually exist? No, because foo.bar was a file. You'll get an error: No such file or directory, because the foobar directory does not exist.

    If I understand what you are trying to do, you are trying to extract the directory that contains the file specified by $Version. The command dirname /path/to/foo.bar will return /path/to. So you want to set New_version=$( dirname "$Version" ), at which point you should be able to cd $New_version.

    P.S. Make sure $Version is reading in an absolute path name, not a relative name, so that it's independent of where you run the script from.