I've somehow managed to screw up bash while fiddling with the $PATH variable in my bash_profile (I think...). All I did, as far as I can remember, was add a directory to the $PATH variable. Please HELP!
Here's what I get when I cd into various directories
my-MacBook-Pro:~ myuser$ cd .rvm
-bash: dirname: command not found
-bash: find: command not found
my-MacBook-Pro:.rvm myuser$ cd
-bash: find: command not found
And here's what happens when I try to get into my .bash_profile to undo whatever it is that I did...
my-MacBook-Pro:~ myuser$ emacs .bash_profile
-bash: emacs: command not found
my-MacBook-Pro:~ myuser$ sudo emacs .bash_profile
-bash: sudo: command not found
Any help would be massively appreciated. I'm completely screwed until I can get bash working normally again!
/usr/bin/emacs .bash_profile or similar should work when the PATH is broken.
The $PATH variable tells the shell where to look for commands. If you just bypass that by telling it the full path, it should work. Try /usr/bin/emacs .bash_profile.
When you do a cd, you're getting a bunch of other things. Since you're using BASH there are are two possible issues:
You have PROMPT_COMMAND defined. Try to undefining it:
$ unset PROMPT_COMMAND
There's an alias of the cd command: This was quite common in Kornshell where you don't have the nice backslashed characters you could put into your prompt string. If you wanted your prompt to have the name of your directory in it.
You had to do something like this:
function _cd
{
logname="$(logname)"
hostname="$(hostname)"
directory="$1"
pattern="$2"
if [ "$pattern" ] #This is a substitution!
then
\cd "$directory" "$pattern"
elif [ "$directory" ]
then
\cd "$directory"
else
\cd
fi
directory=$PWD
shortName=${directory#$HOME}
if [ "$shortName" = "" ]
then
prompt="~$logname"
elif [ "$shortName" = "$directory" ]
then
prompt="$directory"
else
prompt="~$shortName"
fi
title="$logname#$hostname:$prompt"
PS1="$title
$ "
}
alias cd="_cd"
Ugly isn't it? You don't have to go through all of that for BASH, but this does work in BASH too, and I've seen places where this was done either out of ignorance of inertia.
Try this:
$ type cd
You'll either get
$type cd
cd is a shell builtin
or you'll get
$ type cd
cd is an alias for ....
As for your updating of $PATH, you probably forgot to put $PATH back in the new definition, or quotation marks because someone has a directory name with a space in it. Your PATH setting should look like this:
PATH="/my/directory:$PATH"
Some people say it should be:
PATH="$PATH:/my/directory"
I guess, that you have defined $PROMPT_COMMAND (maybe in .bashrc) in a way that uses dirname and find.
That would explain the behavior of cd.
The find command is by default in /usr/bin/find. Thus, you can use it to find the locations of your imprtant commands and reconstruct you path information.
Related
I have a file .aliases that I point to in my .zshrc file
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
if [ -f $DIR"/.aliases" ]; then
. $DIR"/.aliases"
fi
This code is the same in my .bashrc file (in the process of switching over to zsh). The aliases work fine when I open a new terminal - however when I change directory and open tmux, the aliases break. At first I thought this had something to do with whether the directory is the correct one - however, when I switch to bash, it works! So I am very confused as to what is causing this issue.
BASH_SOURCE cannot be used in .zshrc, because it is a bash-specific variable that isn't defined in zsh. You'll have to replace it with its zsh equivalent, found here.
Can anybody explain what is wrong with my terminal:
$ echo $PATH
=/usr/local/bin
$ ls
-bash: ls: command not found
$ cd
-bash: find: command not found
Why won't these commands work? Help? Anyone?
I'm guessing your .bash_profile or .bashrc has a line that looks like
export PATH=/usr/local/bin
This is overwriting all the existing stuff that needs to be in your $PATH. You need to change this line to look like
export PATH=/usr/local/bin:$PATH
"ls" lives in "/bin" and "find" lives in "/usr/bin". You need to add these to your $PATH in your bash_profile or .bashrc.
Like most makefiles, I have some bash scripts that use variables for executables. For example, $mysql_exec for /usr/bin/mysql. I would like to be able to say something like:
mysql_exec=mysql
to use $PATH or
mysql_exec=/usr/bin/mysql
to get an absolute location without $PATH. I also want to check to see if the executable is valid using something like this:
if [ ! -x $mysql_exec ] ...
However, this command:
if [ ! -x "mysql" ]; then print "oh oh"; fi
Actually prints "oh oh", even though mysql is in my $PATH. From the command-line, typing mysql has the same effect as typing /usr/bin/mysql. So, how do I get bash really check to see if $mysql_exec is an executable ($PATH and all)?
In Bash, you can use the built-in type -P to force a resolution against the PATH or type -p to show the path only if there's no alias or function by that name. Using type avoids calling an external such as which.
Something like this may do what you're looking for:
[ -x "$(type -p "$mysql_exec")" ]
whether you use
mysql_exec=mysql
or
mysql_exec=/usr/bin/mysql
which is a small program that checks $PATH for a program specified as an argument:
$ which mysql
/usr/bin/mysql
Another useful utility (that isn't installed on all systems but is included in GNU CoreUtils) is readlink. readlink can give you back a full and absolute path, without symlinks. For example:
$ cd ~me/bin
$ ln -s `which mysql` mysupersql
$ readlink -f mysupersql
/usr/bin/mysql
I often use a combination of both so I know that the path is both absolute and not a symlink:
mysql_exec=$(readlink -f `which mysql`)
if [ ! -x "$mysql_exec" ] ; then
...
To add to Kaleb's answer, you an also check if the file is a symlink using if [-L $file] and follow that symlink if you can't install readlink. The rest of the check though remains as the way Kaleb mentioned.
I'm writing a Bash script. I need the current working directory to always be the directory that the script is located in.
The default behavior is that the current working directory in the script is that of the shell from which I run it, but I do not want this behavior.
#!/bin/bash
cd "$(dirname "$0")"
The following also works:
cd "${0%/*}"
The syntax is thoroughly described in this StackOverflow answer.
Try the following simple one-liners:
For all UNIX/OSX/Linux
dir="$(cd -P -- "$(dirname -- "$0")" && pwd -P)"
Bash
dir="$(cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
Note: A double dash (--) is used in commands to signify the end of command options, so files containing dashes or other special characters won't break the command.
Note: In Bash, use ${BASH_SOURCE[0]} in favor of $0, otherwise the path can break when sourcing it (source/.).
*For Linux, Mac and other BSD:
cd "$(dirname "$(realpath -- "$0")")";
Note: realpath should be installed in the most popular Linux distribution by default (like Ubuntu), but in some it can be missing, so you have to install it.
Note: If you're using Bash, use ${BASH_SOURCE[0]} in favor of $0, otherwise the path can break when sourcing it (source/.).
Otherwise you could try something like that (it will use the first existing tool):
cd "$(dirname "$(readlink -f -- "$0" || realpath -- "$0")")"
For Linux specific:
cd "$(dirname "$(readlink -f -- "$0")")"
*Using GNU readlink on BSD/Mac:
cd "$(dirname "$(greadlink -f -- "$0")")"
Note: You need to have coreutils installed
(e.g. 1. Install Homebrew, 2. brew install coreutils).
In bash
In bash you can use Parameter Expansions to achieve that, like:
cd "${0%/*}"
but it doesn't work if the script is run from the same directory.
Alternatively you can define the following function in bash:
realpath () {
[[ "$1" = /* ]] && echo "$1" || echo "$PWD/${1#./}"
}
This function takes 1 argument. If argument has already absolute path, print it as it is, otherwise print $PWD variable + filename argument (without ./ prefix).
or here is the version taken from Debian .bashrc file:
function realpath()
{
f=$#
if [ -d "$f" ]; then
base=""
dir="$f"
else
base="/$(basename -- "$f")"
dir="$(dirname -- "$f")"
fi
dir="$(cd -- "$dir" && /bin/pwd)"
echo "$dir$base"
}
Related:
How to detect the current directory in which I run my shell script?
How do I get the directory where a Bash script is located from within the script itself?
Bash script absolute path with OS X
Reliable way for a Bash script to get the full path to itself
See also:
How can I get the behavior of GNU's readlink -f on a Mac?
cd "$(dirname "${BASH_SOURCE[0]}")"
It's easy. It works.
The accepted answer works well for scripts that have not been symlinked elsewhere, such as into $PATH.
#!/bin/bash
cd "$(dirname "$0")"
However if the script is run via a symlink,
ln -sv ~/project/script.sh ~/bin/;
~/bin/script.sh
This will cd into the ~/bin/ directory and not the ~/project/ directory, which will probably break your script if the purpose of the cd is to include dependencies relative to ~/project/
The symlink safe answer is below:
#!/bin/bash
cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" # cd current directory
readlink -f is required to resolve the absolute path of the potentially symlinked file.
The quotes are required to support filepaths that could potentially contain whitespace (bad practice, but its not safe to assume this won't be the case)
This script seems to work for me:
#!/bin/bash
mypath=`realpath $0`
cd `dirname $mypath`
pwd
The pwd command line echoes the location of the script as the current working directory no matter where I run it from.
There are a lot of correct answers in here, but one that tends to be more useful for me (making sure a script's relative paths remain predictable/work) is to use pushd/popd:
pushd "$(dirname ${BASH_SOURCE:0})"
trap popd EXIT
# ./xyz, etc...
This will push the source file's directory on to a navigation stack, thereby changing the working directory, but then, when the script exits (for whatever reason, including failure), the trap will run popd, restoring the current working directory before it was executed. If the script were to cd and then fail, your terminal could be left in an unpredictable state after the execution ends - the trap prevents this.
I take this and it works.
#!/bin/bash
cd "$(dirname "$0")"
CUR_DIR=$(pwd)
Get the real path to your script
if [ -L $0 ] ; then
ME=$(readlink $0)
else
ME=$0
fi
DIR=$(dirname $ME)
(This is answer to the same my question here: Get the name of the directory where a script is executed)
cd "`dirname $(readlink -f ${0})`"
Most answers either don't handle files which are symlinked via a relative path, aren't one-liners or don't handle BSD (Mac). A solution which does all three is:
HERE=$(cd "$(dirname "$BASH_SOURCE")"; cd -P "$(dirname "$(readlink "$BASH_SOURCE" || echo .)")"; pwd)
First, cd to bash's conception of the script's directory. Then readlink the file to see if it is a symlink (relative or otherwise), and if so, cd to that directory. If not, cd to the current directory (necessary to keep things a one-liner). Then echo the current directory via pwd.
You could add -- to the arguments of cd and readlink to avoid issues of directories named like options, but I don't bother for most purposes.
You can see the full explanation with illustrations here:
https://www.binaryphile.com/bash/2020/01/12/determining-the-location-of-your-script-in-bash.html
echo $PWD
PWD is an environment variable.
If you just need to print present working directory then you can follow this.
$ vim test
#!/bin/bash
pwd
:wq to save the test file.
Give execute permission:
chmod u+x test
Then execute the script by ./test then you can see the present working directory.
How can I find out where an alias is defined on my system? I am referring to the kind of alias that is used within a Terminal session launched from Mac OS X (10.6.3).
For example, if I enter the alias command with no parameters at a Terminal command prompt, I get a list of aliases that I have set, for example:
alias mysql='/usr/local/mysql/bin/mysql'
However, I have searched all over my system using Spotlight and mdfind in various startup files and so far can not find where this alias has been defined. ( I did it a long time ago and didn't write down where I assigned the alias).
For OSX, this 2-step sequence worked well for me, in locating an alias I'd created long ago and couldn't locate in expected place (~/.zshrc).
cweekly:~ $ which la
la: aliased to ls -lAh
cweekly:~$ grep -r ' ls -lAh' ~
/Users/cweekly//.oh-my-zsh/lib/aliases.zsh:alias la='ls -lAh'
Aha! "Hiding" in ~/.oh-my-zsh/lib/aliases.zsh. I had poked around a bit in .oh-my-zsh but had overlooked lib/aliases.zsh.
you can just simply type in alias on the command prompt to see what aliases you have. Otherwise, you can do a find on the most common places where aliases are defined, eg
grep -RHi "alias" /etc /root
First use the following commands
List all functions
functions
List all aliases
alias
If you aren't finding the alias or function consider a more aggressive searching method
Bash version
bash -ixlc : 2>&1 | grep thingToSearchHere
Zsh version
zsh -ixc : 2>&1 | grep thingToSearchHere
Brief Explanation of Options
-i Force shell to be interactive.
-c Take the first argument as a command to execute
-x -- equivalent to --xtrace
-l Make bash act as if invoked as a login shell
Also in future these are the standard bash config files
/etc/profile
~/.bash_profile or ~/.bash_login or ~/.profile
~/.bash_logout
~/.bashrc
More info: http://www.heimhardt.com/htdocs/bashrcs.html
A bit late to the party, but I was having the same problem (trying to find where the "l." command was aliased in RHEL6), and ended up in a place not mentioned in the previous answers. It may not be found in all bash implementations, but if the /etc/profile.d/ directory exists, try grepping there for unexplained aliases. That's where I found:
[user#server ~]$ grep l\\. /etc/profile.d/*
/etc/profile.d/colorls.csh:alias l. 'ls -d .*'
/etc/profile.d/colorls.csh:alias l. 'ls -d .* --color=auto'
/etc/profile.d/colorls.sh: alias l.='ls -d .*' 2>/dev/null
/etc/profile.d/colorls.sh:alias l.='ls -d .* --color=auto' 2>/dev/null
The directory isn't mentioned in the bash manpage, and isn't properly part of where bash searches for profile/startup info, but in the case of RHEL you can see the calling code within /etc/profile:
for i in /etc/profile.d/*.sh ; do
if [ -r "$i" ]; then
if [ "${-#*i}" != "$-" ]; then
. "$i"
else
. "$i" >/dev/null 2>&1
fi
fi
done
Please do check custom installations/addons/plugins you have added, in addition to the .zshrc/.bashrc/.profile etc files
So for me: it was git aliased to 'g'.
$ which g
g: aliased to git
Then I ran the following command to list all aliases
$ alias
I found a whole lot of git related aliases that I knew I had not manually added.
This got me thinking about packages or configurations I had installed. And so went to the
.oh-my-zsh
directory. Here I ran the following command:
$ grep -r 'git' . |grep -i alias
And lo and behold, I found my alias in :
./plugins/git/git.plugin.zsh
I found the answer ( I had been staring at the correct file but missed the obvious ).
The aliases in my case are defined in the file ~/.bash_profile
Somehow this eluded me.
For more complex setups (e.g. when you're using a shell script framework like bash-it, oh-my-zsh or the likes) it's often useful to add 'alias mysql' at key positions in your scripts. This will help you figure out exactly when the alias is added.
e.g.:
echo "before sourcing .bash-it:"
alias mysql
. $HOME/.bash-it/bash-it.sh
echo "after sourcing bash:"
alias mysql
I think that maybe this is similar to what ghostdog74 meant however their command didn't work for me.
I would try something like this:
for i in `find . -type f`; do # find all files in/under current dir
echo "========"
echo $i # print file name
cat $i | grep "alias" # find if it has alias and if it does print the line containing it
done
If you wanted to be really fancy you could even add an if [[ grep -c "alias" ]] then <print file name>
The only reliable way of finding where the alias could have been defined is by analyzing the list of files opened by bash using dtruss.
If
$ csrutil status
System Integrity Protection status: enabled.
you won't be able to open bash and you may need a copy.
$ cp /bin/bash mybash
$ $ codesign --remove-signature mybash
and then use
sudo dtruss -t open ./mybash -ic exit 2>&1 | awk -F'"' '/^open/ {print substr($2, 0, length($2)-2)}'
to list all the files where the alias could have been defined, like
/dev/dtracehelper
/dev/tty
/usr/share/locale/en_CA.UTF-8/LC_MESSAGES/BASH.mo
/usr/share/locale/en_CA.utf8/LC_MESSAGES/BASH.mo
/usr/share/locale/en_CA/LC_MESSAGES/BASH.mo
/usr/share/locale/en.UTF-8/LC_MESSAGES/BASH.mo
/usr/share/locale/en.utf8/LC_MESSAGES/BASH.mo
/usr/share/locale/en/LC_MESSAGES/BASH.mo
/Users/user/.bashrc
/Users/user/.bash_aliases
/Users/user/.bash_history
...
Try: alias | grep name_of_alias
Ex.: alias | grep mysql
or, as already mentioned above
which name_of_alias
In my case, I use Oh My Zsh, so I put aliases definition in ~/.zshrc file.