Can't use folder path with tilde in rmdir

770 views Asked by At

I need to be able to remove a directory that is relative to the Documents folder of any user's system.

rmdir: ~/Documents/Folder: No such file or directory

If I manually enter the expanded path (/Users/ricky/Documents/Folder), it works fine.

I thought bash automatically expanded the tilde at the beginning of paths?

Update:

After trying a bunch of different approaches as recommended, I'm pretty confident now that the issue is with how I'm storing the path. I'm getting the path from a text file which I read line by line:

...
export_folder_path="$(echo $line | cut -f2 -d=)"
...

echo $export_folder_path
rmdir $export_folder_path
rmdir "$HOME/Documents/Folder\ 1"

This outputs the following:

$HOME/Documents/Folder\ 1
rmdir: $HOME/Documents/Folder\ 1: No such file or directory
rmdir: /Users/ricky/Documents/Folder\ 1: Directory not empty (This is actually what I want)

I can't work out what the difference between my manually typing the export path and using the variable. Why is the variable refusing to expand $HOME? I have tried many variations of adding quotations with no luck.

1

There are 1 answers

2
P.P On

Tilde expansion doesn't work in all cases. You can instead use the HOME variable:

rmdir $HOME/Documents/Folder

From bash manual:

Tilde Expansion If a word begins with an unquoted tilde character ('~'), all of the characters preceding the first unquoted slash (or all characters, if there is no unquoted slash) are considered a tilde-prefix. If none of the characters in the tilde-prefix are quoted, the characters in the tilde-prefix following the tilde are treated as a possible login name. If this login name is the null string, the tilde is replaced with the value of the shell parameter HOME. If HOME is unset, the home directory of the user executing the shell is substituted instead. Otherwise, the tilde-prefix is replaced with the home directory associated with the specified login name.

If the tilde-prefix is a '~+', the value of the shell variable PWD replaces the tilde-prefix. If the tilde-prefix is a '~-', the value of the shell variable OLDPWD, if it is set, is substituted. If the characters following the tilde in the tilde-prefix consist of a number N, optionally prefixed by a '+' or a '-', the tilde-prefix is replaced with the corresponding element from the directory st, as it would be displayed by the dirs builtin invoked with the tilde- prefix as an argument. If the characters following the tilde in the tilde-prefix consist of a number without a leading '+' or '-', '+' is assumed.

If the login name is invalid, or the tilde expansion fails, the word is unchanged.