Home > Enterprise >  Why can't cd into the target folder?
Why can't cd into the target folder?

Time:10-18

Write a multiple lines alias command:

alias cdvf='(ID=$(id -u $USER);
             gvfs_uri="mtp:host=Xiaomi_Redmi_10A_IJLZKJLNNRLBSSVO/Internal shared storage/Android/data";
             echo "$gvfs_uri";
             dfolder="/run/user/$ID/gvfs/""$gvfs_uri";
             echo "$dfolder";
             cd "$dfolder")'

Trace the run time commamd:

set -x

Now paste the alias in console,call my alias--cdvf: It never enter into target folder /Android/data,but the last command is parsed as cd '/run/user/1000/gvfs/mtp:host=Xiaomi_Redmi_10A_IJLZKJLNNRLBSSVO/Internal shared storage/Android/data' by bash.

debian@debian:~$ cdvf
   id -u debian
  ID=1000
  gvfs_uri='mtp:host=Xiaomi_Redmi_10A_IJLZKJLNNRLBSSVO/Internal shared storage/Android/data'
  echo 'mtp:host=Xiaomi_Redmi_10A_IJLZKJLNNRLBSSVO/Internal shared storage/Android/data'
mtp:host=Xiaomi_Redmi_10A_IJLZKJLNNRLBSSVO/Internal shared storage/Android/data
  dfolder='/run/user/1000/gvfs/mtp:host=Xiaomi_Redmi_10A_IJLZKJLNNRLBSSVO/Internal shared storage/Android/data'
  echo '/run/user/1000/gvfs/mtp:host=Xiaomi_Redmi_10A_IJLZKJLNNRLBSSVO/Internal shared storage/Android/data'
/run/user/1000/gvfs/mtp:host=Xiaomi_Redmi_10A_IJLZKJLNNRLBSSVO/Internal shared storage/Android/data
  cd '/run/user/1000/gvfs/mtp:host=Xiaomi_Redmi_10A_IJLZKJLNNRLBSSVO/Internal shared storage/Android/data'
debian@debian:~$ 
debian@debian:~$ cd '/run/user/1000/gvfs/mtp:host=Xiaomi_Redmi_10A_IJLZKJLNNRLBSSVO/Internal shared storage/Android/data'
  cd '/run/user/1000/gvfs/mtp:host=Xiaomi_Redmi_10A_IJLZKJLNNRLBSSVO/Internal shared storage/Android/data'
debian@debian:/run/user/1000/gvfs/mtp:host=Xiaomi_Redmi_10A_IJLZKJLNNRLBSSVO/Internal shared storage/Android/data$ 
debian@debian:/run/user/1000/gvfs/mtp:host=Xiaomi_Redmi_10A_IJLZKJLNNRLBSSVO/Internal shared storage/Android/data$ 

Copy the last line into terminal and run,it entered into target folder,why cdvf can't enter into target folder /Android/data?

CodePudding user response:

It is changing to that directory. However, you use () in your alias: that creates a subshell. In the subshell, you're in the right directory, but then the subshell exits, and you're in the directory you were in before (in the "current" shell).

Remove the parentheses from your alias.

I assume you use parentheses to avoid polluting your shell with the variables. You'll want to use a function instead:

cdvf() {
    local ID gvfs_uri dfolder
    ID=$(id -u "$USER")
    gvfs_uri="mtp:host=Xiaomi_Redmi_10A_IJLZKJLNNRLBSSVO/Internal shared storage/Android/data"
    echo "$gvfs_uri"
    dfolder="/run/user/$ID/gvfs/$gvfs_uri"
    echo "$dfolder"
    cd "$dfolder"
}

As the bash manual says in Aliases

For almost every purpose, shell functions are preferred over aliases.

  • Related