In Windows 10 WSL Bash and Linux Bash command line/console, let’s write an override script that allows the cd command to move to a directory not only by specifying a directory but also by specifying a file.
yuis ASUS /mnt/c/pg$ cd ruby/hoge.md
yuis ASUS /mnt/c/pg/ruby$ cd -
/mnt/c/pg
yuis ASUS /mnt/c/pg$
Something like an override.
cd(){
[[ -f "${1}" ]] && builtin cd "$(dirname "${1}")" || builtin cd "${1}"
}
When I want to move to a directory where a file is located with Everything, I can copy the full path of the file with ctrl+shift+C, but I can’t copy the folder path. I thought it would be tedious to do dirname each time, so I tried to modify cd, but it was surprisingly troublesome.
[bash - Override a builtin command with an alias - Stack Overflow](https://stackoverflow.com/questions/28783509/override-a-builtin-command-with-an-alias)because it calls recursively the cd defined by you. To fix, use the builtin keyword like:
So if you change builtin cd to cd, it will bug. I don’t think command cd will work either.
cd has surprisingly unstable or indefinite arguments, so if you try to specify it in detail, you’ll get stuck. For example, there are values like -, .., ./, where realpath doesn’t work, so it’s better to only process things that are definitively “arguments are files” and let all other ambiguous things go through normal operations, so you won’t be troubled by bugs later on.