display message on command "cd production" - linux

I wish to accomplish the following:
If I execute "cd production" on bash prompt, I should go into the directory and a message should be displayed "You are in production", so that the user gets warned.

Don't do it that way. :)
What you really want to know isn't whether the user just got into the 'production' directory via a cd command; what you really want to know is if you're modifying production data, and how you got there (cd, pushd, popd, opening a shell from a parent process in that directory already) is irrelevant.
It makes much more sense, then, to have your shell put up an obnoxious warning when you're in the production directory.
function update_prompt() {
if [[ $PWD =~ /production(/|$) ]] ; then
PS1="\u#\h \w [WARNING: PRODUCTION] $"
else
PS1="\u#\h \w $"
fi
}
PROMPT_COMMAND=update_prompt
Feel free to replace the strings in question with something much more colorful.

You can do it by executing the following in the shell context (e.g., .bashrc).
xcd() {
if [[ "$1" == "production" ]] ; then
echo Warning, you are in production.
fi
builtin cd $1
}
alias cd=xcd
This creates a function then aliases the cd command to that function. The function itself provides the warning then calls the real cd.
A better solution, however, may be to detect real paths, since the solution you've asked for will give you a false positive for "cd $HOME ; cd production" and false negative for "cd /production/x" (if /production was indeed the danger area).
I would do something like:
#!/bin/bash
export xcd_warn="/home/pax /tmp"
xcd() {
builtin cd $1
export xcd_path=$(pwd)
for i in ${xcd_warn} ; do
echo ${xcd_path}/ | grep "^${i}/"
if [[ $? -eq 0 ]] ; then
echo Warning, you are in ${i}.
fi
done
}
alias cd=xcd
which will allow you to configure the top-level danger directories as absolute paths.

Related

"mkdir || echo && exit" exiting even when mkdir succeeds

mkdir $2 || echo "I can't create directory $2" && exit 8
Hi everyone, this is my first post here, so be kind.
I am making a script right now and this line troubles me.
The exit 8 should happen only if the directory $2 cannot be created.
After running the script and successfully creating that directory, it still exits on 8.
Am I missing something? I thought the command after " || " happens only if you get a false on the left side.
I am new to the Linux world, and as a guy with a little to medium C experience I am confused, help! (using ubuntu, bash, btw)
As #fernand0 suggested, the problem is the precedence of the || and && operators. You want it to run something like mkdir || ( echo && exit ) -- that is, run the echo && exit part if mkdir fails. But what it's actually doing is running something like ( mkdir || echo ) && exit -- that is, it runs the exit part if either the mkdir OR echo command succeeds. echo will almost always succeed, so it'll almost always exit.
So, you need to explicitly group the commands, to override this precedence. But don't use ( ), because that runs its contents in a subshell, and exit will just exit the subshell, not the main script; you can use { } instead, or use an explicit if block. Also, you don't actually want echo && exit, because that runs exit only if the echo command succeeds. echo almost always succeeds, but in the rare case that it fails I'm pretty sure you want the script to exit anyway.
When I need to do something like this in a script, I usually use this idiom:
mkdir "$2" || {
echo "I can't create directory $2" >&2
exit 8
}
(Note: as #CharlesDuffy suggested, I added double-quotes around $2 -- double-quoting variable references is almost always a good idea in case they contain any spaces, wildcards, etc. I also sent the error message to standard error (>&2) instead of standard output, which is also generally a better way to do things.)
If you want to be terser, you can put it all on one line:
mkdir "$2" || { echo "I can't create directory $2" >&2; exit 8; }
Note that the final ; (or a line break) is required before the }, or the shell thinks } is just an argument to exit. You could also go the other way and use an explicit if block:
if ! mkdir "$2"; then
echo "I can't create directory $2" >&2
exit 8
fi
This option is less clever and concise, but that's a good thing -- clever and concise is exactly what caused this problem in the first place; clear and unambiguous is much better for code.
|| and && do not have the precedence you are accustomed to in other languages. Unparenthesized, it is equivalent to (a || b) && c (strictly left-to-right), not a || (b && c) (where && has higher precedence than ||). It's rarely a good idea to chain commands together with a mix of || and &&; instead, use an if statement.
if ! mkdir "$2"; then
echo "I can't create directory $2" >&2
exit 8
fi
If you really want to use the list operators, use { ... } to group commands appropriately.
mkdir "$2" || { echo "I can't create directory $2" >&2; exit 8; }

Bash script lost shebang path after instantiate function

I am writing a script with a iterative menu to run command lines. However, after create the iterative menu I got a error when I want run the commands.
The error is [COMMAND]No such file or directory linux.
#!/bin/bash
ATESTS=("TEST NAME 1" "TESTE NAME 2")
PATH=("test1.xml" "text2.xml")
menu () {
for i in ${!ATESTS[#]}; do
printf "%3d%s) %s\n" $((i+1)) "${OPT[i]:- }" "${ATESTS[i]}"
done
[[ "$msg" ]] && echo "$msg"; :
}
prompt="Check an ATEST (again to uncheck, ENTER when done): "
while menu && read -rp "$prompt" num && [[ "$num" ]]; do
/usr/bin/clear;
[[ "$num" != *[![:digit:]]* ]] &&
(( num > 0 && num <= ${#ATESTS[#]} )) ||
{ msg="Invalid ATEST: $num"; continue; }
((num--)); msg="${ATESTS[num]} was ${OPT[num]:+un}checked"
[[ "${OPT[num]}" ]] && OPT[num]="" || OPT[num]="+"
done
for i in ${!ATESTS[#]}; do
[[ "${OPT[i]}" ]] && { printf "%s " "${ATESTS[i]}"; msg=""; }
done
echo "$msg"
for i in ${!ATESTS[#]}; do
if [[ "${OPT[i]}" ]] && [[ $PWD = /repo/$USER/program ]]; then
find . -iname ${PATH[i]} -exec cat {} \;
fi
done
I want find a *.xml file then execute with a script that already exist and belong to /usr/bin. However the find command dont execute and also the cat command in this example, getting the following error ([COMMAND]No such file or directory linux.)
if i try run one bash command before the function, the command execute without any problem, but after the function the commands fails.
I create one alias to the script for running inside /repo/$USER/program without include the path to the script.
The problem has nothing to do with the shebang or the function. The problem is that you're using the variable $PATH. This variable tells the system what directories to search for executable commands, so when you set it to an array... it's going to start looking for commands in the locations(s) specified by ${PATH[0]}, which is "test1.xml", which is not even a directory let alone one that contains all of the executables you need.
Solution: don't use the variable name PATH for anything other than the list of directories to search for commands. In fact, since this is one of a large number of all-uppercase variables that have special functions, it's best to use lowercase (or mixed-case) variables in your scripts, to avoid weird conflicts like this.
BTW, I can't tell if the rest of the script makes sense or not; your use of short-circuit booleans for conditional execution (e.g. this && that || do something) makes it really hard to follow the logic. I'd strongly recommend using if blocks for conditional execution (as you did in the for loop at the end); they make it much easier to tell what's going on.

How to suppress Error printed by shell commands. [duplicate]

How would I validate that a program exists, in a way that will either return an error and exit, or continue with the script?
It seems like it should be easy, but it's been stumping me.
Answer
POSIX compatible:
command -v <the_command>
Example use:
if ! command -v <the_command> &> /dev/null
then
echo "<the_command> could not be found"
exit
fi
For Bash specific environments:
hash <the_command> # For regular commands. Or...
type <the_command> # To check built-ins and keywords
Explanation
Avoid which. Not only is it an external process you're launching for doing very little (meaning builtins like hash, type or command are way cheaper), you can also rely on the builtins to actually do what you want, while the effects of external commands can easily vary from system to system.
Why care?
Many operating systems have a which that doesn't even set an exit status, meaning the if which foo won't even work there and will always report that foo exists, even if it doesn't (note that some POSIX shells appear to do this for hash too).
Many operating systems make which do custom and evil stuff like change the output or even hook into the package manager.
So, don't use which. Instead use one of these:
command -v foo >/dev/null 2>&1 || { echo >&2 "I require foo but it's not installed. Aborting."; exit 1; }
type foo >/dev/null 2>&1 || { echo >&2 "I require foo but it's not installed. Aborting."; exit 1; }
hash foo 2>/dev/null || { echo >&2 "I require foo but it's not installed. Aborting."; exit 1; }
(Minor side-note: some will suggest 2>&- is the same 2>/dev/null but shorter – this is untrue. 2>&- closes FD 2 which causes an error in the program when it tries to write to stderr, which is very different from successfully writing to it and discarding the output (and dangerous!))
If your hash bang is /bin/sh then you should care about what POSIX says. type and hash's exit codes aren't terribly well defined by POSIX, and hash is seen to exit successfully when the command doesn't exist (haven't seen this with type yet). command's exit status is well defined by POSIX, so that one is probably the safest to use.
If your script uses bash though, POSIX rules don't really matter anymore and both type and hash become perfectly safe to use. type now has a -P to search just the PATH and hash has the side-effect that the command's location will be hashed (for faster lookup next time you use it), which is usually a good thing since you probably check for its existence in order to actually use it.
As a simple example, here's a function that runs gdate if it exists, otherwise date:
gnudate() {
if hash gdate 2>/dev/null; then
gdate "$#"
else
date "$#"
fi
}
Alternative with a complete feature set
You can use scripts-common to reach your need.
To check if something is installed, you can do:
checkBin <the_command> || errorMessage "This tool requires <the_command>. Install it please, and then run this tool again."
The following is a portable way to check whether a command exists in $PATH and is executable:
[ -x "$(command -v foo)" ]
Example:
if ! [ -x "$(command -v git)" ]; then
echo 'Error: git is not installed.' >&2
exit 1
fi
The executable check is needed because bash returns a non-executable file if no executable file with that name is found in $PATH.
Also note that if a non-executable file with the same name as the executable exists earlier in $PATH, dash returns the former, even though the latter would be executed. This is a bug and is in violation of the POSIX standard. [Bug report] [Standard]
Edit: This seems to be fixed as of dash 0.5.11 (Debian 11).
In addition, this will fail if the command you are looking for has been defined as an alias.
I agree with lhunath to discourage use of which, and his solution is perfectly valid for Bash users. However, to be more portable, command -v shall be used instead:
$ command -v foo >/dev/null 2>&1 || { echo "I require foo but it's not installed. Aborting." >&2; exit 1; }
Command command is POSIX compliant. See here for its specification: command - execute a simple command
Note: type is POSIX compliant, but type -P is not.
It depends on whether you want to know whether it exists in one of the directories in the $PATH variable or whether you know the absolute location of it. If you want to know if it is in the $PATH variable, use
if which programname >/dev/null; then
echo exists
else
echo does not exist
fi
otherwise use
if [ -x /path/to/programname ]; then
echo exists
else
echo does not exist
fi
The redirection to /dev/null/ in the first example suppresses the output of the which program.
I have a function defined in my .bashrc that makes this easier.
command_exists () {
type "$1" &> /dev/null ;
}
Here's an example of how it's used (from my .bash_profile.)
if command_exists mvim ; then
export VISUAL="mvim --nofork"
fi
Expanding on #lhunath's and #GregV's answers, here's the code for the people who want to easily put that check inside an if statement:
exists()
{
command -v "$1" >/dev/null 2>&1
}
Here's how to use it:
if exists bash; then
echo 'Bash exists!'
else
echo 'Your system does not have Bash'
fi
Try using:
test -x filename
or
[ -x filename ]
From the Bash manpage under Conditional Expressions:
-x file
True if file exists and is executable.
To use hash, as #lhunath suggests, in a Bash script:
hash foo &> /dev/null
if [ $? -eq 1 ]; then
echo >&2 "foo not found."
fi
This script runs hash and then checks if the exit code of the most recent command, the value stored in $?, is equal to 1. If hash doesn't find foo, the exit code will be 1. If foo is present, the exit code will be 0.
&> /dev/null redirects standard error and standard output from hash so that it doesn't appear onscreen and echo >&2 writes the message to standard error.
Command -v works fine if the POSIX_BUILTINS option is set for the <command> to test for, but it can fail if not. (It has worked for me for years, but I recently ran into one where it didn't work.)
I find the following to be more failproof:
test -x "$(which <command>)"
Since it tests for three things: path, existence and execution permission.
There are a ton of options here, but I was surprised no quick one-liners. This is what I used at the beginning of my scripts:
[[ "$(command -v mvn)" ]] || { echo "mvn is not installed" 1>&2 ; exit 1; }
[[ "$(command -v java)" ]] || { echo "java is not installed" 1>&2 ; exit 1; }
This is based on the selected answer here and another source.
If you check for program existence, you are probably going to run it later anyway. Why not try to run it in the first place?
if foo --version >/dev/null 2>&1; then
echo Found
else
echo Not found
fi
It's a more trustworthy check that the program runs than merely looking at PATH directories and file permissions.
Plus you can get some useful result from your program, such as its version.
Of course the drawbacks are that some programs can be heavy to start and some don't have a --version option to immediately (and successfully) exit.
Check for multiple dependencies and inform status to end users
for cmd in latex pandoc; do
printf '%-10s' "$cmd"
if hash "$cmd" 2>/dev/null; then
echo OK
else
echo missing
fi
done
Sample output:
latex OK
pandoc missing
Adjust the 10 to the maximum command length. It is not automatic, because I don't see a non-verbose POSIX way to do it:
How can I align the columns of a space separated table in Bash?
Check if some apt packages are installed with dpkg -s and install them otherwise.
See: Check if an apt-get package is installed and then install it if it's not on Linux
It was previously mentioned at: How can I check if a program exists from a Bash script?
I never did get the previous answers to work on the box I have access to. For one, type has been installed (doing what more does). So the builtin directive is needed. This command works for me:
if [ `builtin type -p vim` ]; then echo "TRUE"; else echo "FALSE"; fi
I wanted the same question answered but to run within a Makefile.
install:
#if [[ ! -x "$(shell command -v ghead)" ]]; then \
echo 'ghead does not exist. Please install it.'; \
exit -1; \
fi
It could be simpler, just:
#!/usr/bin/env bash
set -x
# if local program 'foo' returns 1 (doesn't exist) then...
if ! type -P foo; then
echo 'crap, no foo'
else
echo 'sweet, we have foo!'
fi
Change foo to vi to get the other condition to fire.
hash foo 2>/dev/null: works with Z shell (Zsh), Bash, Dash and ash.
type -p foo: it appears to work with Z shell, Bash and ash (BusyBox), but not Dash (it interprets -p as an argument).
command -v foo: works with Z shell, Bash, Dash, but not ash (BusyBox) (-ash: command: not found).
Also note that builtin is not available with ash and Dash.
zsh only, but very useful for zsh scripting (e.g. when writing completion scripts):
The zsh/parameter module gives access to, among other things, the internal commands hash table. From man zshmodules:
THE ZSH/PARAMETER MODULE
The zsh/parameter module gives access to some of the internal hash ta‐
bles used by the shell by defining some special parameters.
[...]
commands
This array gives access to the command hash table. The keys are
the names of external commands, the values are the pathnames of
the files that would be executed when the command would be in‐
voked. Setting a key in this array defines a new entry in this
table in the same way as with the hash builtin. Unsetting a key
as in `unset "commands[foo]"' removes the entry for the given
key from the command hash table.
Although it is a loadable module, it seems to be loaded by default, as long as zsh is not used with --emulate.
example:
martin#martin ~ % echo $commands[zsh]
/usr/bin/zsh
To quickly check whether a certain command is available, just check if the key exists in the hash:
if (( ${+commands[zsh]} ))
then
echo "zsh is available"
fi
Note though that the hash will contain any files in $PATH folders, regardless of whether they are executable or not. To be absolutely sure, you have to spend a stat call on that:
if (( ${+commands[zsh]} )) && [[ -x $commands[zsh] ]]
then
echo "zsh is available"
fi
The which command might be useful. man which
It returns 0 if the executable is found and returns 1 if it's not found or not executable:
NAME
which - locate a command
SYNOPSIS
which [-a] filename ...
DESCRIPTION
which returns the pathnames of the files which would
be executed in the current environment, had its
arguments been given as commands in a strictly
POSIX-conformant shell. It does this by searching
the PATH for executable files matching the names
of the arguments.
OPTIONS
-a print all matching pathnames of each argument
EXIT STATUS
0 if all specified commands are
found and executable
1 if one or more specified commands is nonexistent
or not executable
2 if an invalid option is specified
The nice thing about which is that it figures out if the executable is available in the environment that which is run in - it saves a few problems...
Use Bash builtins if you can:
which programname
...
type -P programname
For those interested, none of the methodologies in previous answers work if you wish to detect an installed library. I imagine you are left either with physically checking the path (potentially for header files and such), or something like this (if you are on a Debian-based distribution):
dpkg --status libdb-dev | grep -q not-installed
if [ $? -eq 0 ]; then
apt-get install libdb-dev
fi
As you can see from the above, a "0" answer from the query means the package is not installed. This is a function of "grep" - a "0" means a match was found, a "1" means no match was found.
This will tell according to the location if the program exist or not:
if [ -x /usr/bin/yum ]; then
echo "This is Centos"
fi
I'd say there isn't any portable and 100% reliable way due to dangling aliases. For example:
alias john='ls --color'
alias paul='george -F'
alias george='ls -h'
alias ringo=/
Of course, only the last one is problematic (no offence to Ringo!). But all of them are valid aliases from the point of view of command -v.
In order to reject dangling ones like ringo, we have to parse the output of the shell built-in alias command and recurse into them (command -v isn't a superior to alias here.) There isn't any portable solution for it, and even a Bash-specific solution is rather tedious.
Note that a solution like this will unconditionally reject alias ls='ls -F':
test() { command -v $1 | grep -qv alias }
If you guys/gals can't get the things in answers here to work and are pulling hair out of your back, try to run the same command using bash -c. Just look at this somnambular delirium. This is what really happening when you run $(sub-command):
First. It can give you completely different output.
$ command -v ls
alias ls='ls --color=auto'
$ bash -c "command -v ls"
/bin/ls
Second. It can give you no output at all.
$ command -v nvm
nvm
$ bash -c "command -v nvm"
$ bash -c "nvm --help"
bash: nvm: command not found
#!/bin/bash
a=${apt-cache show program}
if [[ $a == 0 ]]
then
echo "the program doesn't exist"
else
echo "the program exists"
fi
#program is not literal, you can change it to the program's name you want to check
The hash-variant has one pitfall: On the command line you can for example type in
one_folder/process
to have process executed. For this the parent folder of one_folder must be in $PATH. But when you try to hash this command, it will always succeed:
hash one_folder/process; echo $? # will always output '0'
I second the use of "command -v". E.g. like this:
md=$(command -v mkdirhier) ; alias md=${md:=mkdir} # bash
emacs="$(command -v emacs) -nw" || emacs=nano
alias e=$emacs
[[ -z $(command -v jed) ]] && alias jed=$emacs
I had to check if Git was installed as part of deploying our CI server. My final Bash script was as follows (Ubuntu server):
if ! builtin type -p git &>/dev/null; then
sudo apt-get -y install git-core
fi
To mimic Bash's type -P cmd, we can use the POSIX compliant env -i type cmd 1>/dev/null 2>&1.
man env
# "The option '-i' causes env to completely ignore the environment it inherits."
# In other words, there are no aliases or functions to be looked up by the type command.
ls() { echo 'Hello, world!'; }
ls
type ls
env -i type ls
cmd=ls
cmd=lsx
env -i type $cmd 1>/dev/null 2>&1 || { echo "$cmd not found"; exit 1; }
If there isn't any external type command available (as taken for granted here), we can use POSIX compliant env -i sh -c 'type cmd 1>/dev/null 2>&1':
# Portable version of Bash's type -P cmd (without output on stdout)
typep() {
command -p env -i PATH="$PATH" sh -c '
export LC_ALL=C LANG=C
cmd="$1"
cmd="`type "$cmd" 2>/dev/null || { echo "error: command $cmd not found; exiting ..." 1>&2; exit 1; }`"
[ $? != 0 ] && exit 1
case "$cmd" in
*\ /*) exit 0;;
*) printf "%s\n" "error: $cmd" 1>&2; exit 1;;
esac
' _ "$1" || exit 1
}
# Get your standard $PATH value
#PATH="$(command -p getconf PATH)"
typep ls
typep builtin
typep ls-temp
At least on Mac OS X v10.6.8 (Snow Leopard) using Bash 4.2.24(2) command -v ls does not match a moved /bin/ls-temp.
My setup for a Debian server:
I had the problem when multiple packages contained the same name.
For example apache2. So this was my solution:
function _apt_install() {
apt-get install -y $1 > /dev/null
}
function _apt_install_norecommends() {
apt-get install -y --no-install-recommends $1 > /dev/null
}
function _apt_available() {
if [ `apt-cache search $1 | grep -o "$1" | uniq | wc -l` = "1" ]; then
echo "Package is available : $1"
PACKAGE_INSTALL="1"
else
echo "Package $1 is NOT available for install"
echo "We can not continue without this package..."
echo "Exitting now.."
exit 0
fi
}
function _package_install {
_apt_available $1
if [ "${PACKAGE_INSTALL}" = "1" ]; then
if [ "$(dpkg-query -l $1 | tail -n1 | cut -c1-2)" = "ii" ]; then
echo "package is already_installed: $1"
else
echo "installing package : $1, please wait.."
_apt_install $1
sleep 0.5
fi
fi
}
function _package_install_no_recommends {
_apt_available $1
if [ "${PACKAGE_INSTALL}" = "1" ]; then
if [ "$(dpkg-query -l $1 | tail -n1 | cut -c1-2)" = "ii" ]; then
echo "package is already_installed: $1"
else
echo "installing package : $1, please wait.."
_apt_install_norecommends $1
sleep 0.5
fi
fi
}

Bash: cd to directory provided by program output

I have a short shell program that returns a system path. What I want to do is CD to that path using a bash alias.
My ideal output is
~$ pwd
/home/username
~$ mark home
~$ cd /
/$ pwd
/
/$ place home
~$ pwd
/home/username
I have the "mark" part working, but the "place" is not:
alias place="cd \"~/marker.sh go $#\";"
My idea is that I want to cd to the output of ~/marker.sh go $#
The problem is that bash is interpreting this as one command, and gives the errors:
-bash: cd: ~/marker.sh go : No such file or directory
-bash: home: command not found
which I assume means that the shell is parsing the entire alias as a string.
I've tried various forms of quoting for the shell script part of the alias $(), ``, etc, but they either try to run the script on bash start, or don't execute at all and just remain a string.
I'm programming this mostly to learn bash commands, but I can't figure out this one part!
I'm running OSX 10.9 in iTerm 1.0.0.20130624, if that's important.
Edit: I understand that cd-ing inside a script won't work, which is why I'm trying to just return the correct path using my program and use the built-in alias system to do the actual changing of directories.
You want a function, not an alias:
place () {
cd $( ~/marker.sh go "$#" )
}
Aliases do not take arguments; they simply expand in-place, with the arguments occurring after whatever the alias expanded to.
(You should always prefer a function to an alias unless the function cannot be adapted to do what you want.)
Use functions, not aliases or external bash script!
in your .bashrc or any file sourced by it, or any file that you will manually source, put this fully usable script!
declare -A _mark_dir_hash
mark() {
[[ -z $1 ]] && { listmarks; return 0; }
if [[ -n ${_mark_dir_hash[$1]} ]] && [[ $1 != ${_mark_dir_hash[$1]} ]]; then
echo "Mark $1 was already set to ${_mark_dir_hash[$1]}... replaced with new mark"
fi
_mark_dir_hash[$1]=$(pwd)
}
place() {
[[ -z $1 ]] && { echo >&2 "You must give a mark name to go to!"; return 1; }
[[ -z ${_mark_dir_hash[$1]} ]] && { echo >&2 "Mark $1 unknown!"; return 1; }
cd "${_mark_dir_hash[$1]}"
}
listmarks() {
[[ -z ${!_mark_dir_hash[#]} ]] && { echo "No marks!"; return 0; }
for i in "${!_mark_dir_hash[#]}"; do
printf '%s --> %s\n' "$i" "${!_mark_dir_hash[#]}"
done
}
removemark() {
[[ -z $1 ]] && { echo >&2 "You must give a mark name to remove!"; return 1; }
unset _mark_dir_hash[$1]
}
clearmarks() {
_mark_dir_hash=()
}
Ha, I just realized you're on mac, so you might be stuck with an antique version of bash which doesn't support associative arrays. Too bad for you. Yet, this might be useful to other people using modern shells!

keeping track of a moving shell script

I hope someone can help me out. For the past month or so I have be learning the Bash... I have a program ( a simple language study program ) that I want to be able to install and run from a script.
I have a script that will create a new folder and move itself into it. The way I am doing it at the moment is below, although I have had problems with arrays that I am using later. I was wondering if there was a cleaner way of getting the new path to file name. Any help or insight would be greatly appreciated.
#!/bin/bash
echo "# path to me ---------------> ${0} "
echo "# parent path --------------> ${0%/*} "
echo "# my name ------------------> ${0##*/} "
if [[ ! -d ${0%/*}/SomeNewFolder ]] && [[ ! -d ${0%/*}/../SomeNewFolder ]]
then
mkdir ${0%/*}/SomeNewFolder
mv ${0} ${0%/*}/SomeNewFolder/${0##*/}
fi
echo ${0%/*}
newpath=$(echo "${0%/*}/SomeNewFolder")
echo $newpath
All the best, Ben
exit
For clarity, I would probably declare named variables for your common values instead of constantly reusing the ${0} array. It's also good practice to quote variables and strings.
The only major issue I saw, was running ./script.sh would make $0 equal just the filename, so I add "./" to the beginning in that case.
#!/bin/bash -u
ME="${0}"
if [[ ! "$ME" =~ /^\// ]]; then
ME="./$ME"
fi
PARENT="${ME%/*}"
FILENAME="${ME##*/}"
FOLDER="SomeNewFolder"
NEW="$PARENT/$FOLDER"
if [[ ! -d "$NEW" ]] && [[ "${PARENT%/*}" != "$FOLDER" ]]; then
mkdir "$NEW"
mv "$ME" "$NEW"
fi
echo "$PARENT"
echo "$NEW"
Well, you could do something like this to get an absolute path:
PARENTPATH=$( cd "$( dirname "$0" )" && pwd )
NEWPATH=${PARENTPATH}/SomeNewFolder
me="$0"
newdir=SomeNewFolder
if [[ $me =~ ^/ ]] ; then
full_path="$me"
else
full_path="$PWD/$me"
fi
full_path="${full_path//\/\.\///}" # prettify
path_to_me="${full_path%/*}"
parent_dir="${path_to_me##*/}"
if [ ! "$parent_dir" = "$newdir" ] ; then
mkdir -p "$path_to_me/$newdir"
mv -f "$full_path" "$path_to_me/$newdir/"
fi
Basically similar to what lunixbochs was doing, but with a few minor alterations
lower case variable names so as not to be confused with environment variables
crudely estimates absolute path
-f and -p becuase interactivity is never cool, and why not
Installing and setting up programs is more appropriately done from a make file. Granted, it seems intimidating at first, but the basics, such as what you want, are quite simple. For your project, you would ideally have three item:
your program
your run script
your makefile i.e. your installer
This breaks apart each of these different components, making each of them easier to manage. If you tar them together, you can move the tar file to a new computer and reinstall without any changes. Bash is a wonderful tool, but an installer it is not.
Sample make script below:
.PHONY: all clean
SCRIPT=yourScriptName.sh
SUBFOLDER=someFolder
all: $(SCRIPT)
$(SCRIPT): $(SUBFOLDER)
cp $(SCRIPT) $(SUBFOLDER)
$(SUBFOLDER):
mkdir $(SUBFOLDER)
clean:
-rm -f $(SUBFOLDER)/$(SCRIPT)
-rmdir $(SUBFOLDER)
IMPORTANT! make is whitespace sensitive! Those indents are tabs not four spaces.

Resources