Bash - Expanding variables for command arguments leads to quoting hell - bash

So, I'm scripting an rsync command. I've been fiddling around for the entire day. It's time to ask for help.
My issue appears to be quoting, but it's not obvious to me exactly what's going wrong. This snippet:
#!/bin/bash
sudo -v
COMMAND=`basename ${0}`
SRC='/etc'
SRC=`realpath ${SRC}` # make relative paths absolute
SRC=${SRC}/ # force rsync to disallow symlinks to the parent path
if [[ ! -d ${SRC} ]];
then
echo Use ${COMMAND} to backup directories only
exit 1
fi
BACKUP_DIR='/tmp/backup prep'
TMP_DIR=${BACKUP_DIR}/tmp
DEST=${BACKUP_DIR}/`basename ${SRC}`
LOG_DIR=${TMP_DIR}
LOG_FILE=${LOG_DIR}/${COMMAND}-`date +%Y-%b-%d-%H-%M-%S-%N`.log
for DIR in "${BACKUP_DIR}" "${TMP_DIR}" "${LOG_DIR}"
do
if [[ ! -d "'${DIR}'" ]];
then
echo Creating "'${DIR}'"
sudo mkdir "${DIR}"
fi
done
RSYNC_OPTS=""
#--dry-run, -n
RSYNC_OPTS=${RSYNC_OPTS}" --dry-run"
# --recursive, -r recurse into directories
RSYNC_OPTS=${RSYNC_OPTS}" --recursive"
#--filter=RULE, -f add a file-filtering RULE
RSYNC_OPTS=${RSYNC_OPTS}" --filter='dir-merge,p- .gitignore'"
# --checksum, -c skip based on checksum, not mod-time & size
RSYNC_OPTS=${RSYNC_OPTS}" --checksum"
echo "rsync ${RSYNC_OPTS} '${SRC}' '${DEST}'" | sudo tee "${LOG_FILE}"
echo --------
echo --------
echo
echo
set -x
sudo rsync "${RSYNC_OPTS} '${SRC}' '${DEST}'"
Produces this:
Creating '/tmp/backup prep'
mkdir: cannot create directory ‘/tmp/backup prep’: File exists
Creating '/tmp/backup prep/tmp'
mkdir: cannot create directory ‘/tmp/backup prep/tmp’: File exists
Creating '/tmp/backup prep/tmp'
mkdir: cannot create directory ‘/tmp/backup prep/tmp’: File exists
rsync --dry-run --recursive --filter='dir-merge,p- .gitignore' --checksum '/etc/' '/tmp/backup prep/etc'
--------
+ sudo rsync ' --dry-run --recursive --filter='\''dir-merge,p- .gitignore'\'' --checksum '\''/etc/'\'' '\''/tmp/backup prep/etc'\'''
rsync: [sender] change_dir "/home/aaron/bin/ --dry-run --recursive --filter='dir-merge,p- .gitignore' --checksum '/etc/' '/tmp/backup prep" failed: No such file or directory (2)
rsync error: some files/attrs were not transferred (see previous errors) (code 23) at main.c(1333) [sender=3.2.3]
And appears to do nothing.
The thing is, if I sudo the echoed command line, sudo rsync --dry-run --recursive --filter='dir-merge,p- .gitignore' --checksum '/etc/' '/tmp/backup prep/etc'
Everything seems to work as expected.
Shell expansion gets me every bloody time. It'd be nice if there were a command that'd show you what the hell is going on.

Here is my finished script. Many thanks to the commentors on my question. With your hints I was able to make progress.
For what it's worth, the objective was to periodically back up a /etc that is using etckeeper and keep the .git repo, but ignore stuff in .gitignore
Some observations:
When building a list of arguments for a command, an array is totally the way to go.
When using the array, the shell beautifully quotes values with spaces. Yo can see this by using set -x in the script below.
Using set -x is really helpful.
When you're struggling to get something working shellcheck is an amazing diagnostic tool.
#!/bin/bash
COMMAND=$(basename "${0}")
SRC="/etc"
BACKUP_DIR="/root/backup prep"
TMP_DIR="${BACKUP_DIR}/tmp"
LOG_DIR="${TMP_DIR}"
if ! sudo -v
then
echo ${COMMAND} quitting...
exit 1
fi
SRC=$(realpath "${SRC}") # make relative paths absolute
SRC="${SRC}"/ # force rsync to disallow symlinks to the parent path
# https://www.shellcheck.net/wiki/SC2086
# Note that $( ) starts a new context, and variables in it have to
# be quoted independently
LOG_FILE="${LOG_DIR}/${COMMAND}-$(date +%Y-%b-%d-%H-%M-%S-%N).log"
for DIR in "${BACKUP_DIR}" "${TMP_DIR}" "${LOG_DIR}"
do
if sudo test ! -d "${DIR}";
then
echo Creating "${DIR}"
sudo mkdir "${DIR}"
fi
done
RSYNC_OPTS=()
# ------------------------------------
# -------------Testing----------------
# ------------------------------------
#
#--dry-run, -n
#RSYNC_OPTS+=("--dry-run")
# ------------------------------------
# -------------Verbosity--------------
# ------------------------------------
#
# --verbose, -v increase verbosity
#RSYNC_OPTS+=("--verbose")
# --progress show progress during transfer
#RSYNC_OPTS+=("--progress")
# --itemize-changes, -i output a change-summary for all updates
#RSYNC_OPTS+=("--itemize-changes")
# --stats give some file-transfer stats
#RSYNC_OPTS+=("--stats")
# --human-readable, -h output numbers in a human-readable format
RSYNC_OPTS+=("--human-readable")
# --log-file=FILE log what we're doing to the specified FILE
RSYNC_OPTS+=("--log-file=${LOG_FILE}")
# --log-file-format=FMT log updates using the specified FMT
# ------------------------------------
# -------------Permissions------------
# ------------------------------------
#
# --owner, -o preserve owner (super-user only)
RSYNC_OPTS+=("--owner")
# --group, -g preserve group
RSYNC_OPTS+=("--group")
# --perms, -p preserve permissions
RSYNC_OPTS+=("--perms")
# --xattrs, -X preserve extended attributes
RSYNC_OPTS+=("--xattrs")
# --acls, -A preserve ACLs (implies --perms)
RSYNC_OPTS+=("--acls")
# ------------------------------------
# -------------Times------------------
# ------------------------------------
#
# --times, -t preserve modification times
RSYNC_OPTS+=("--times")
# --crtimes, -N preserve create times (newness)
# rsync: This rsync does not support --crtimes (-N)
# RSYNC_OPTS+=("--crtimes")
# --atimes, -U preserve access (use) times
RSYNC_OPTS+=("--atimes")
# --open-noatime avoid changing the atime on opened files
RSYNC_OPTS+=("--open-noatime")
# ------------------------------------
# -------------Where------------------
# ------------------------------------
#
# --mkpath create the destination's path component
RSYNC_OPTS+=("--mkpath")
# --recursive, -r recurse into directories
RSYNC_OPTS+=("--recursive")
# --links, -l copy symlinks as symlinks
RSYNC_OPTS+=("--links")
# Rsync can also distinguish "safe" and "unsafe" symbolic links. An
# example where this might be used is a web site mirror that wishes to
# ensure that the rsync module that is copied does not include symbolic
# links to /etc/passwd in the public section of the site. Using
# --copy-unsafe-links will cause any links to be copied as the file they
# point to on the destination. Using --safe-links will cause unsafe
# links to be omitted altogether. (Note that you must specify --links
# for --safe-links to have any effect.)
# --copy-unsafe-links where the link would point outside of the new tree, copy the file
RSYNC_OPTS+=("--copy-unsafe-links")
# --hard-links, -H preserve hard links
RSYNC_OPTS+=("--hard-links")
# --one-file-system, -x don't cross filesystem boundaries
RSYNC_OPTS+=("--one-file-system")
# ------------------------------------
# -------------Exclusions-------------
# ------------------------------------
#
#--filter=RULE, -f add a file-filtering RULE
RSYNC_OPTS+=("--filter=dir-merge,p- .gitignore")
# --delete-excluded also delete excluded files from dest dirs
RSYNC_OPTS+=("--delete-excluded")
#--delete-after receiver deletes after transfer, not during
RSYNC_OPTS+=("--delete-after")
# --force force deletion of dirs even if not empty
RSYNC_OPTS+=("--force")
# --update, -u skip files that are newer on the receiver
#RSYNC_OPTS=${RSYNC_OPTS}" --update")
# ------------------------------------
# -------------Misc-------------------
# ------------------------------------
#
# --protect-args, -s no space-splitting; wildcard chars only
# This option sends all filenames and most options to the remote rsync
# without allowing the remote shell to interpret them.
RSYNC_OPTS+=("--protect-args")
# --checksum, -c skip based on checksum, not mod-time & size
RSYNC_OPTS+=("--checksum")
# --temp-dir=DIR, -T create temporary files in directory DIR
RSYNC_OPTS+=("--temp-dir=${TMP_DIR}")
#echo sudo rsync "${RSYNC_OPTS[#]}" "'${SRC}'" "'${DEST}'"
#echo
#set -x
sudo rsync "${RSYNC_OPTS[#]}" "${SRC}" "${DEST}"

Related

Configure bash_history to show the pwd of each command [duplicate]

I'd like to save the current directory where the each command was issued alongside the command in the history. In order not to mess things up, I was thinking about adding the current directory as a comment at the end of the line. An example might help:
$ cd /usr/local/wherever
$ grep timmy accounts.txt
I'd like bash to save the last command as:
grep timmy accounts.txt # /usr/local/wherever
The idea is that this way I could immediately see where I issued the command.
One-liner version
Here is a one-liner version. It's the original. I've also posted a short function version and a long function version with several added features. I like the function versions because they won't clobber other variables in your environment and they're much more readable than the one-liner. This post has some information on how they all work which may not be duplicated in the others.
Add the following to your ~/.bashrc file:
export PROMPT_COMMAND='hpwd=$(history 1); hpwd="${hpwd# *[0-9]* }"; if [[ ${hpwd%% *} == "cd" ]]; then cwd=$OLDPWD; else cwd=$PWD; fi; hpwd="${hpwd% ### *} ### $cwd"; history -s "$hpwd"'
This makes a history entry that looks like:
rm subdir/file ### /some/dir
I use ### as a comment delimiter to set it apart from comments that the user might type and to reduce the chance of collisions when stripping old path comments that would otherwise accumulate if you press enter on a blank command line. Unfortunately, the side affect is that a command like echo " ### " gets mangled, although that should be fairly rare.
Some people will find the fact that I reuse the same variable name to be unpleasant. Ordinarily I wouldn't, but here I'm trying to minimize the footprint. It's easily changed in any case.
It blindly assumes that you aren't using HISTTIMEFORMAT or modifying the history in some other way. It would be easy to add a date command to the comment in lieu of the HISTTIMEFORMAT feature. However, if you need to use it for some reason, it still works in a subshell since it gets unset automatically:
$ htf="%Y-%m-%d %R " # save it for re-use
$ (HISTTIMEFORMAT=$htf; history 20)|grep 11:25
There are a couple of very small problems with it. One is if you use the history command like this, for example:
$ history 3
echo "hello world" ### /home/dennis
ls -l /tmp/file ### /home/dennis
history 3
The result will not show the comment on the history command itself, even though you'll see it if you press up-arrow or issue another history command.
The other is that commands with embedded newlines leave an uncommented copy in the history in addition to the commented copy.
There may be other problems that show up. Let me know if you find any.
How it works
Bash executes a command contained in the PROMPT_COMMAND variable each time the PS1 primary prompt is issued. This little script takes advantage of that to grab the last command in the history, add a comment to it and save it back.
Here it is split apart with comments:
hpwd=$(history 1) # grab the most recent command
hpwd="${hpwd# *[0-9]* }" # strip off the history line number
if [[ ${hpwd%% *} == "cd" ]] # if it's a cd command, we want the old directory
then # so the comment matches other commands "where *were* you when this was done?"
cwd=$OLDPWD
else
cwd=$PWD
fi
hpwd="${hpwd% ### *} ### $cwd" # strip off the old ### comment if there was one so they
# don't accumulate, then build the comment
history -s "$hpwd" # replace the most recent command with itself plus the comment
hcmnt - long function version
Here is a long version in the form of a function. It's a monster, but it adds several useful features. I've also posted a one-liner (the original) and a shorter function. I like the function versions because they won't clobber other variables in your environment and
they're much more readable than the one-liner. Read the entry for the one-liner and the commments in the function below for additional information on how it works and some limitations. I've posted each version in its own answer in order to keep things more organized.
To use this one, save it in a file called hcmnt in a location like /usr/local/bin (you can chmod +x it if you want) then source it in your ~/.bashrc like this:
source /usr/local/bin/hcmnt
export hcmntextra='date "+%Y%m%d %R"'
export PROMPT_COMMAND='hcmnt'
Don't edit the function's file where PROMPT_COMMAND or hcmntextra are set. Leave them as is so they remain as defaults. Include them in your .bashrc as shown above and edit them there to set options for hcmnt or to change or unset hcmntextra. Unlike the short function, with this one you must both have the hcmntextra variable set and use the -e option to make that feature work.
You can add several options which are documented (with a couple of examples) in the comments in the function. One notable feature is to have the history entry with appended comment logged to a file and leave the actual history untouched. In order to use this function, just
add the -l filename option like so:
export PROMPT_COMMAND="hcmnt -l ~/histlog"
You can use any combination of options, except that -n and -t are mutually exclusive.
#!/bin/bash
hcmnt() {
# adds comments to bash history entries (or logs them)
# by Dennis Williamson - 2009-06-05 - updated 2009-06-19
# http://stackoverflow.com/questions/945288/saving-current-directory-to-bash-history
# (thanks to Lajos Nagy for the idea)
# the comments can include the directory
# that was current when the command was issued
# plus optionally, the date or other information
# set the bash variable PROMPT_COMMAND to the name
# of this function and include these options:
# -e - add the output of an extra command contained in the hcmntextra variable
# -i - add ip address of terminal that you are logged in *from*
# if you're using screen, the screen number is shown
# if you're directly logged in, the tty number or X display number is shown
# -l - log the entry rather than replacing it in the history
# -n - don't add the directory
# -t - add the from and to directories for cd commands
# -y - add the terminal device (tty)
# text or a variable
# Example result for PROMPT_COMMAND='hcmnt -et $LOGNAME'
# when hcmntextra='date "+%Y%m%d %R"'
# cd /usr/bin ### mike 20090605 14:34 /home/mike -> /usr/bin
# Example for PROMPT_COMMAND='hcmnt'
# cd /usr/bin ### /home/mike
# Example for detailed logging:
# when hcmntextra='date "+%Y%m%d %R"'
# and PROMPT_COMMAND='hcmnt -eityl ~/.hcmnt.log $LOGNAME#$HOSTNAME'
# $ tail -1 ~/.hcmnt.log
# cd /var/log ### dave#hammerhead /dev/pts/3 192.168.1.1 20090617 16:12 /etc -> /var/log
# INSTALLATION: source this file in your .bashrc
# will not work if HISTTIMEFORMAT is used - use hcmntextra instead
export HISTTIMEFORMAT=
# HISTTIMEFORMAT still works in a subshell, however, since it gets unset automatically:
# $ htf="%Y-%m-%d %R " # save it for re-use
# $ (HISTTIMEFORMAT=$htf; history 20)|grep 11:25
local script=$FUNCNAME
local hcmnt=
local cwd=
local extra=
local text=
local logfile=
local options=":eil:nty"
local option=
OPTIND=1
local usage="Usage: $script [-e] [-i] [-l logfile] [-n|-t] [-y] [text]"
local newline=$'\n' # used in workaround for bash history newline bug
local histline= # used in workaround for bash history newline bug
local ExtraOpt=
local LogOpt=
local NoneOpt=
local ToOpt=
local tty=
local ip=
# *** process options to set flags ***
while getopts $options option
do
case $option in
e ) ExtraOpt=1;; # include hcmntextra
i ) ip="$(who --ips -m)" # include the terminal's ip address
ip=($ip)
ip="${ip[4]}"
if [[ -z $ip ]]
then
ip=$(tty)
fi;;
l ) LogOpt=1 # log the entry
logfile=$OPTARG;;
n ) if [[ $ToOpt ]]
then
echo "$script: can't include both -n and -t."
echo $usage
return 1
else
NoneOpt=1 # don't include path
fi;;
t ) if [[ $NoneOpt ]]
then
echo "$script: can't include both -n and -t."
echo $usage
return 1
else
ToOpt=1 # cd shows "from -> to"
fi;;
y ) tty=$(tty);;
: ) echo "$script: missing filename: -$OPTARG."
echo $usage
return 1;;
* ) echo "$script: invalid option: -$OPTARG."
echo $usage
return 1;;
esac
done
text=($#) # arguments after the options are saved to add to the comment
text="${text[*]:$OPTIND - 1:${#text[*]}}"
# *** process the history entry ***
hcmnt=$(history 1) # grab the most recent command
# save history line number for workaround for bash history newline bug
histline="${hcmnt% *}"
hcmnt="${hcmnt# *[0-9]* }" # strip off the history line number
if [[ -z $NoneOpt ]] # are we adding the directory?
then
if [[ ${hcmnt%% *} == "cd" ]] # if it's a cd command, we want the old directory
then # so the comment matches other commands "where *were* you when this was done?"
if [[ $ToOpt ]]
then
cwd="$OLDPWD -> $PWD" # show "from -> to" for cd
else
cwd=$OLDPWD # just show "from"
fi
else
cwd=$PWD # it's not a cd, so just show where we are
fi
fi
if [[ $ExtraOpt && $hcmntextra ]] # do we want a little something extra?
then
extra=$(eval "$hcmntextra")
fi
# strip off the old ### comment if there was one so they don't accumulate
# then build the string (if text or extra aren't empty, add them plus a space)
hcmnt="${hcmnt% ### *} ### ${text:+$text }${tty:+$tty }${ip:+$ip }${extra:+$extra }$cwd"
if [[ $LogOpt ]]
then
# save the entry in a logfile
echo "$hcmnt" >> $logfile || echo "$script: file error." ; return 1
else
# workaround for bash history newline bug
if [[ $hcmnt != ${hcmnt/$newline/} ]] # if there a newline in the command
then
history -d $histline # then delete the current command so it's not duplicated
fi
# replace the history entry
history -s "$hcmnt"
fi
} # END FUNCTION hcmnt
# set a default (must use -e option to include it)
export hcmntextra='date "+%Y%m%d %R"' # you must be really careful to get the quoting right
# start using it
export PROMPT_COMMAND='hcmnt'
update 2009-06-19: Added options useful for logging (ip and tty), a workaround for the duplicate entry problem, removed extraneous null assignments
You could install Advanced Shell History, an open source tool that writes your bash or zsh history to a sqlite database. This records things like the current working directory, the command exit code, command start and stop times, session start and stop times, tty, etc.
If you want to query the history database, you can write your own SQL queries, save them and make them available within the bundled ash_query tool. There are a few useful prepackaged queries, but since I know SQL pretty well, I usually just open the database and query interactively when I need to look for something.
One query I find very useful, though, is looking at the history of the current working directory. It helps me remember where I left off when I was working on something.
vagrant#precise32:~$ ash_query -q CWD
session
when what
1
2014-08-27 17:13:07 ls -la
2014-08-27 17:13:09 cd .ash
2014-08-27 17:16:27 ls
2014-08-27 17:16:33 rm -rf advanced-shell-history/
2014-08-27 17:16:35 ls
2014-08-27 17:16:37 less postinstall.sh
2014-08-27 17:16:57 sudo reboot -n
And the same history using the current working directory (and anything below it):
vagrant#precise32:~$ ash_query -q RCWD
session
where
when what
1
/home/vagrant/advanced-shell-history
2014-08-27 17:11:34 nano ~/.bashrc
2014-08-27 17:12:54 source /usr/lib/advanced_shell_history/bash
2014-08-27 17:12:57 source /usr/lib/advanced_shell_history/bash
2014-08-27 17:13:05 cd
/home/vagrant
2014-08-27 17:13:07 ls -la
2014-08-27 17:13:09 cd .ash
/home/vagrant/.ash
2014-08-27 17:13:10 ls
2014-08-27 17:13:11 ls -l
2014-08-27 17:13:16 sqlite3 history.db
2014-08-27 17:13:43 ash_query
2014-08-27 17:13:50 ash_query -Q
2014-08-27 17:13:56 ash_query -q DEMO
2014-08-27 17:14:39 ash_query -q ME
2014-08-27 17:16:26 cd
/home/vagrant
2014-08-27 17:16:27 ls
2014-08-27 17:16:33 rm -rf advanced-shell-history/
2014-08-27 17:16:35 ls
2014-08-27 17:16:37 less postinstall.sh
2014-08-27 17:16:57 sudo reboot -n
FWIW - I'm the author and maintainer of the project.
hcmnts - short function version
Here is a short version in the form of a function. I've also posted a one-liner (the original) and a longer function with several added features. I like the function versions because they won't clobber other variables in your environment and they're much more readable than the one-liner. Read the entry for the one-liner for additional information on how this works and some limitations. I've posted each version in its own answer in order to keep things more organized.
To use this one, save it in a file called hcmnts in a location like /usr/local/bin (you can chmod +x it if you want) then source it in your ~/.bashrc like this:
source /usr/local/bin/hcmnts
Comment out the line that sets hcmntextra if you don't want the date and time (or you can change its format or use some other command besides date).
That's all there is to it.
#!/bin/bash
hcmnts() {
# adds comments to bash history entries
# the *S*hort version of hcmnt (which has many more features)
# by Dennis Williamson
# http://stackoverflow.com/questions/945288/saving-current-directory-to-bash-history
# (thanks to Lajos Nagy for the idea)
# INSTALLATION: source this file in your .bashrc
# will not work if HISTTIMEFORMAT is used - use hcmntextra instead
export HISTTIMEFORMAT=
# HISTTIMEFORMAT still works in a subshell, however, since it gets unset automatically:
# $ htf="%Y-%m-%d %R " # save it for re-use
# $ (HISTTIMEFORMAT=$htf; history 20)|grep 11:25
local hcmnt
local cwd
local extra
hcmnt=$(history 1)
hcmnt="${hcmnt# *[0-9]* }"
if [[ ${hcmnt%% *} == "cd" ]]
then
cwd=$OLDPWD
else
cwd=$PWD
fi
extra=$(eval "$hcmntextra")
hcmnt="${hcmnt% ### *}"
hcmnt="$hcmnt ### ${extra:+$extra }$cwd"
history -s "$hcmnt"
}
export hcmntextra='date +"%Y%m%d %R"'
export PROMPT_COMMAND='hcmnts'
For those who want this in zsh I've modified Jeet Sukumaran's implementation and percol to allow interactive keyword searching and extraction of either the command or path it was executed in. It's also possible to filter out duplicate commands and hide fields (date, command, path)
Here's a one liner of what I use. Sticking it here because it's vastly simpler, and I have no problem with per-session history, I just also want to have a history with the working directory.
Also the one-liner above mucks with your user interface too much.
export PROMPT_COMMAND='if [ "$(id -u)" -ne 0 ]; then echo "$(date "+%Y-%m-%d.%H:%M:%S") $(pwd) $(history 1)" >> ~/.bash.log; fi'
Since my home dir is typically a cross-mounted gluster thingy, this has the side effect of being a history of everything I've ever done. Optionally add $(hostname) to the echo command above... depending on your working environment.
Even with 100k entries, grep is more than good enough. No need to sqlite log it. Just don't type passwords on the command line and you're good. Passwords are 90's tech anyway!
Also, for searching I tend to do this:
function hh() {
grep "$1" ~/.bash.log
}
Gentleman this works better.. The only thing I can not figure out is how to make the script NOT log to syslog on login and log the last command in history. But works like a charm so far.
#!/bin/bash
trackerbash() {
# adds comments to bash history entries
# by Dennis Williamson
# http://stackoverflow.com/questions/945288/saving-current-directory-to-bash-history
# (thanks to Lajos Nagy for the idea)
#Supper Enhanced by QXT
# INSTALLATION: source this file in your .bashrc
export HISTTIMEFORMAT=
# export HISTTIMEFORMAT='%F %T '
local hcmnt
local cwd
local extra
local thistty
local whoiam
local sudouser
local shelldate
local TRACKIP
local TRACKHOST
thistty=`/usr/bin/tty|/bin/cut -f3-4 -d/`
whoiam=`/usr/bin/whoami`
sudouser=`last |grep $thistty |head -1 | awk '{ print $1 }' |cut -c 1-10`
hcmnt=$(history 1)
hcmnt="${hcmnt# *[0-9]* }"
cwd=`pwd`
hcmnt="${hcmnt% ### *}"
hcmnt=" $hcmnt ${extra:+$extra }"
shelldate=`date +"%Y %b %d %R:%S"`
TRACKHOST=`whoami | sed -r "s/.*\((.*)\).*/\\1/"`
TRACKIP=`last |grep $thistty |head -1 | awk '{ print $3 }'`
logger -p local1.notice -t bashtracker -i -- "$sudouser ${USER}: $thistty: $TRACKIP: $shelldate: $cwd : $hcmnt"
history -w
}
export PROMPT_COMMAND='trackerbash'
Full disclosure: I'm the author of the FOSS-tool
shournal - A (file-) journal for your shell:
Using it's bash integration, the working directory of a command is also stored within shournal's sqlite-database and can be retrieved via
shournal --query -cmdcwd "$PWD"
Querying for sub-working-directories can be done with
shournal --query -cmdcwd -like "$PWD/%"
You could consider an independent project (I wrote it) that supports saving the path for each command: https://github.com/chrissound/MoscoviumOrange
Where you can add a hook into Bash to save each entry with:
$(jq -n --arg command "$1" --arg path "$PWD" '{"command":$command, "path":$path}' | "$(echo 'readlink -f $(which nc)' | nix run nixpkgs.netcat)" -N -U ~/.config/moscoviumOrange/monitor.soc &)

bash: git_prompt: command not found

I'm getting this Annoying git_prompt: command not found error. I got a new Mac, and I'm trying to use my old .bash_profile into the new computer. I used Thoughtbot's laptop configuration which worked well last time.
I'm running on Mac Os Sierra, here is my .bash_profile:
# Configuring Our Prompt
# ======================
# if you install git via homebrew, or install the bash autocompletion via homebrew, you get __git_ps1 which you can use in the PS1
# to display the git branch. it's supposedly a bit faster and cleaner than manually parsing through sed. i dont' know if you care
# enough to change it
# This function is called in your prompt to output your active git branch.
function parse_git_branch {
git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
# This function builds your prompt. It is called below
function prompt {
# Define some local colors
local LIGHT_RED="\[\033[1;31m\]" # really understood
local CHAR="theAsteve :" local BLUE="\[\e[0;49;34m\]"
# ♥ ☆ - Keeping some cool ASCII Characters for reference
# Here is where we actually export the PS1 Variable which stores the text for your prompt
export PS1="theAsteve$ "
PS2='> '
PS4='+ '
}
# Finally call the function and our prompt is all pretty
prompt
export NODE_PATH="/usr/local/lib/node_modules:$NODE_PATH"
export GIT_MERGE_AUTOEDIT='no'
# Editors
# Tells your shell that when a program requires various editors, use sublime.
# The -w flag tells your shell to wait until sublime exits
export VISUAL="vim"
export SVN_EDITOR="vim"
export GIT_EDITOR="vim"
export EDITOR="vim"
# Version
# What version of the Flatiron School bash profile this is
# Paths
# The USR_PATHS variable will just store all relevant /usr paths for easier usage
# Each path is seperate via a : and we always use absolute paths.
# A bit about the /usr directory
# The /usr directory is a convention from linux that creates a common place to put
# files and executables that the entire system needs access too. It tries to be user
# independent, so whichever user is logged in should have permissions to the /usr directory.
# We call that /usr/local. Within /usr/local, there is a bin directory for actually
# storing the binaries (programs) that our system would want.
# Also, Homebrew adopts this convetion so things installed via Homebrew
# get symlinked into /usr/local
export USR_PATHS="/usr/local:/usr/local/bin:/usr/local/sbin:/usr/bin"
# Hint: You can interpolate a variable into a string by using the $VARIABLE notation as below.
# We build our final PATH by combining the variables defined above
# along with any previous values in the PATH variable.
# Our PATH variable is special and very important. Whenever we type a command into our shell,
# it will try to find that command within a directory that is defined in our PATH.
# Read http://blog.seldomatt.com/blog/2012/10/08/bash-and-the-one-true-path/ for more on that.
export PATH="$USR_PATHS:$PATH"
# If you go into your shell and type: echo $PATH you will see the output of your current path.
# For example, mine is:
# /Users/avi/.rvm/gems/ruby-1.9.3-p392/bin:/Users/avi/.rvm/gems/ruby-1.9.3-p392#global/bin:/Users/avi/.rvm/rubies/ruby-1.9.3-p392/bin:/Users/avi/.rvm/bin:/usr/local:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/local/mysql/bin:/usr/local/share/python:/bin:/usr/sbin:/sbin:
# Helpful Functions
# =====================
# A function to CD into the desktop from anywhere
# so you just type desktop.
# HINT: It uses the built in USER variable to know your OS X username
# USE: desktop
# desktop subfolder
function desktop {
cd /Users/$USER/Desktop/$#
}
# A function to easily grep for a matching process
# USE: psg postgres
function psg {
FIRST=`echo $1 | sed -e 's/^\(.\).*/\1/'`
REST=`echo $1 | sed -e 's/^.\(.*\)/\1/'`
ps aux | grep "[$FIRST]$REST"
}
#==================================
# GOLANG PATH
#=================================
export GOPATH=/usr/local/go/bin/go
export PATH=$PATH:$GOPATH/bin
# A function to extract correctly any archive based on extension
# USE: extract imazip.zip
# extract imatar.tar
function extract () {
if [ -f $1 ] ; then
case $1 in
*.tar.bz2) tar xjf $1 ;;
*.tar.gz) tar xzf $1 ;;
*.bz2) bunzip2 $1 ;;
*.rar) rar x $1 ;;
*.gz) gunzip $1 ;;
*.tar) tar xf $1 ;;
*.tbz2) tar xjf $1 ;;
*.tgz) tar xzf $1 ;;
*.zip) unzip $1 ;;
*.Z) uncompress $1 ;;
*) echo "'$1' cannot be extracted via extract()" ;;
esac
else
echo "'$1' is not a valid file"
fi
}
# Bash completion has been installed to:
# /usr/local/etc/bash_completion.d
[[ -r "/usr/local/etc/profile.d/bash_completion.sh" ]] && . "/usr/local/etc/profile.d/bash_completion.sh"
# Case-Insensitive Auto Completion
bind "set completion-ignore-case on"
# Postgres
export PATH=/Applications/Postgres.app/Contents/Versions/9.4/bin:$PATH
if [ -f `brew --prefix`/etc/bash_completion ]; then
. `brew --prefix`/etc/bash_completion
fi
# ===============================================================
# History
# ===============================================================
# Larger bash history
export HISTSIZE=32768
export HISTFILESIZE=$HISTSIZE
# ---------------------
# Colors
# ---------------------
# Adds colors to LS
export CLICOLOR=1
# http://geoff.greer.fm/lscolors/
export LSCOLORS=bxexcxdxbxegedabagacad
# prompt colors
BLACK="\[\e[0;30m\]"
RED="\033[1;31m"
ORANGE="\033[1;33m"
GREEN="\033[1;32m"
PURPLE="\033[1;35m"
WHITE="\033[1;37m"
YELLOW="\[\e[0;33m\]"
CYAN="\[\e[0;36m\]"
BLUE="\[\e[0;34m\]"
BOLD=""
RESET="\033[m"
#----------------------
# style the prompt
# ---------------------
style_user="\[${RESET}${WHITE}\]"
style_path="\[${RESET}${CYAN}\]"
style_chars="\[${RESET}${WHITE}\]"
style_branch="${RED}"
# A more colorful prompt
# \[\e[0m\] resets the color to default color
c_reset='\[\e[0m\]'
# \e[0;31m\ sets the color to red
c_path='\[\e[0;31m\]'
# \e[0;32m\ sets the color to green
c_git_clean='\[\e[0;32m\]'
# \e[0;31m\ sets the color to red
c_git_dirty='\[\e[0;31m\]'
# ---------------------
# Build the prompt
# ---------------------
# Example with committed changes: username ~/documents/GA/wdi on master[+]
__GIT_PROMPT_DIR=$(brew --prefix)/opt/bash-git-prompt/share
[ -f /usr/local/etc/bash_completion ] && . /usr/local/etc/bash_completion || {
# if not found in /usr/local/etc, try the brew --prefix location
[ -f "$(brew --prefix)/etc/bash_completion.d/git-completion.bash" ] && \
. $(brew --prefix)/etc/bash_completion.d/git-completion.bash
}
source ~/.bash_git
# PS1 is the variable for the prompt you see everytime you hit enter
PS1+="${style_user}\u" # Username
PS1+="${style_path} \w" # Working directory
PS1+="\$(prompt_git)" # Git details
PS1+="\n" # Newline
PS1+="${style_chars}\$ \[${RESET}\]" # $ (and reset color)
export PS1='\t H#\! \u:\w$(__git_ps1 "{%s}") -->> '
I tried some of the other posts regarding the same issue. I tried going over the following code without success. -bash: __git_ps1: command not found
At
I've used this feature for years and this works when adding to the bottom of ~/.bashrc
Setup & Config source: https://github.com/jimeh/git-aware-prompt
function parse_git_branch () {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
YELLOW="\[\033[0;33m\]"
GREEN="\[\033[0;32m\]"
NO_COLOR="\[\033[0m\]"
PS1="$GREEN\u#\h$NO_COLOR:\w$YELLOW\$(parse_git_branch)$NO_COLOR\$ "
Here's what it looks like:
user#server:~/dev/project (Some-Branch-Feature)$
You will have to toy around with it to your liking but hope it gets you somewhere.

Mac Terminal search and move files not containing pattern in name

I use a program to rip radio music. Sadly one can not set the temporary folder apart from the folder where the finished mp3's end up later. So I cannot set the output folder to auto add to iTunes.
I'm alright in coding java and what not but have no experience with shell scripts.
I need a script that iterates through all the files within a folder like every 10 minutes and moves them to a different location if they don't start with the string "Track". All temp files are called "Track..." so it should only move finished ones then. Could anyone give me a help getting started?
Thanks!
Here's an example script. You should set the DESTINATION directory properly before uncommenting the line which moves the files. Otherwise, you may end up moving them somewhere undesirable.
In the terminal, cd to the location where you save the snippet below and run the following commands to execute.
Prep work:
cd /save/location
chmod +x file_mover.sh # makes the file executable
Schedule a job:
crontab -e
*/10 * * * * /path/to/file_mover.sh
crontab -l # view list of scheduled jobs
With some minor tweaks you can make this accept CLI options.
#!/bin/bash
# files to skip
REGEX='^TRACK'
# location to move the files
DESTINATION=/tmp/mydir
# directory to read from
# PWD is the working directory
TARGET=${PWD}
# make the directory(ies) if it doesn't exists
if [ ! -f ${DESTINATION} ]; then
mkdir -p ${DESTINATION}
fi
# get the collection of files in the
for FILE in $( ls ${TARGET} )
do
# if the current file does not begin with TRACK, move it
if [[ ! ${FILE} =~ ${REGEX} ]]; then
echo ${FILE}
# SET THE DESTINATION DIRECTORY BEFORE UNCOMMENTING THE LINE BELOW
# if [ -f ${FILE} ]; then # uncomment if you want to
# ensure it's a file and not a directory
# mv ${FILE} ${DESTINATION} # move the file
# fi # uncomment to ensure it's a file (end if)
fi
done
Edit the crontab with EDITOR=nano crontab -e and add a line like this:
*/10 * * * * shopt -s extglob; mv ~/Music/Temp/!(Track)*.mp3 ~/Music/iTunes/iTunes\ Media/Automatically\ Add\ to\ iTunes.localized/
shopt -s extglob adds support for !(). See /usr/share/doc/bash/bash.html.

Cygwin .bashrc PATH gets duplicate entries

I've got the following variable set in my cygwin $HOME/.bashrc
PATH=/bin:/usr/sbin:"/cygdrive/c/Program Files/Java/jdk1.6.0_26/bin":$PATH
Problem is that when I login and the .bashrc gets executed, I get starting duplicates as follows:
Dragos#dragos ~
$ echo $PATH | tr ':' '\n'
/bin
/usr/sbin
/cygdrive/c/Program Files/Java/jdk1.6.0_26/bin
/bin
/usr/sbin
/cygdrive/c/Program Files/Java/jdk1.6.0_26/bin
/usr/local/bin
/usr/bin
/cygdrive/c/WINDOWS
/cygdrive/c/WINDOWS/system32
/cygdrive/c/WINDOWS/System32/Wbem
/cygdrive/c/curl
/
/cygdrive/c/gnupg
/cygdrive/c/Progra~1/cvsnt
/cygdrive/c/Progra~1/GNU/WinCvs 2.0
/cygdrive/c/Progra~1/Notepad++
/cygdrive/c/Progra~1/PuTTY
/cygdrive/c/Progra~1/WinSCP
/cygdrive/c/Python26
/cygdrive/c/Python26/Lib/site-packages/PyQt4/bin
/cygdrive/c/Python26/Scripts
/usr/bin
/usr/lib/lapack
Does anyone know what causes this?
Here's my .bashrc
$ cat ~/.bashrc
# base-files version 3.7-1
# To pick up the latest recommended .bashrc content,
# look in /etc/defaults/etc/skel/.bashrc
# Modifying /etc/skel/.bashrc directly will prevent
# setup from updating it.
# The copy in your home directory (~/.bashrc) is yours, please
# feel free to customise it to create a shell
# environment to your liking. If you feel a change
# would be benificial to all, please feel free to send
# a patch to the cygwin mailing list.
# User dependent .bashrc file
# Shell Options
# #############
# See man bash for more options...
# Don't wait for job termination notification
# set -o notify
# Don't use ^D to exit
# set -o ignoreeof
# Use case-insensitive filename globbing
# shopt -s nocaseglob
# Make bash append rather than overwrite the history on disk
# shopt -s histappend
# When changing directory small typos can be ignored by bash
# for example, cd /vr/lgo/apaache would find /var/log/apache
# shopt -s cdspell
# Completion options
# ##################
# These completion tuning parameters change the default behavior of bash_completion:
# Define to access remotely checked-out files over passwordless ssh for CVS
# COMP_CVS_REMOTE=1
# Define to avoid stripping description in --option=description of './configure --help'
# COMP_CONFIGURE_HINTS=1
# Define to avoid flattening internal contents of tar files
# COMP_TAR_INTERNAL_PATHS=1
# If this shell is interactive, turn on programmable completion enhancements.
# Any completions you add in ~/.bash_completion are sourced last.
# case $- in
# *i*) [[ -f /etc/bash_completion ]] && . /etc/bash_completion ;;
# esac
# History Options
# ###############
# Don't put duplicate lines in the history.
# export HISTCONTROL="ignoredups"
# Ignore some controlling instructions
# export HISTIGNORE="[ ]*:&:bg:fg:exit"
# Whenever displaying the prompt, write the previous line to disk
# export PROMPT_COMMAND="history -a"
# Aliases
# #######
# Some example alias instructions
# If these are enabled they will be used instead of any instructions
# they may mask. For example, alias rm='rm -i' will mask the rm
# application. To override the alias instruction use a \ before, ie
# \rm will call the real rm not the alias.
# Interactive operation...
# alias rm='rm -i'
# alias cp='cp -i'
# alias mv='mv -i'
# Default to human readable figures
# alias df='df -h'
# alias du='du -h'
# Misc :)
# alias less='less -r' # raw control characters
# alias whence='type -a' # where, of a sort
# alias grep='grep --color' # show differences in colour
# Some shortcuts for different directory listings
alias ls='ls -hF --color=tty' # classify files in colour
# alias dir='ls --color=auto --format=vertical'
# alias vdir='ls --color=auto --format=long'
# alias ll='ls -l' # long list
# alias la='ls -A' # all but . and ..
# alias l='ls -CF' #
# Functions
# #########
# Some example functions
# function settitle() { echo -ne "\e]2;$#\a\e]1;$#\a"; }
# Notepad++ function
# Pass in a UNIX path
# Starts notepad++ given a UNIX path argument
function notepadpp() {
local notepadUnixPath="/cygdrive/c/Program Files/Notepad++/notepad++.exe"
#local notepadArgPath=$(eval $(echo cygpath -w -a "$*"))
local notepadArgPath=`cygpath -w -a "$*"`
"$notepadUnixPath" -multiInst "$notepadArgPath" &
}
alias notepad++=notepadpp
# Explorer function
# Pass in a UNIX path
# Starts explorer given a UNIX path argument
function explorer() {
local explorerArgPath=`cygpath -w -a "$*"`
cmd /C start "" "$explorerArgPath" &
}
alias vi=vim
# Change filename starting with prefix string to another prefix string
alias mvprefix='$HOME/mvprefix.sh'
# Change filename ending with suffix string to another suffix string
alias mvsuffix='$HOME/mvsuffix.sh'
# Change filename ending with suffix string to a string prefixed with todays date
alias todaysuffix='$HOME/todaysuffix.sh'
# Generate secure passwords by default
alias pwgen='pwgen -y -c -s -n'
export INPUTRC=$HOME/.inputrc
export EDITOR=vim
export PATH=/bin:/usr/sbin:"/cygdrive/c/Program Files/Java/jdk1.6.0_26/bin":$PATH
# Overwrite DOS env variable APPDATA with our own for installing perl CPANPLUS
export APPDATA=$HOME
Here's my .bash_profile
$ cat .bash_profile
# base-files version 3.7-1
# To pick up the latest recommended .bash_profile content,
# look in /etc/defaults/etc/skel/.bash_profile
# Modifying /etc/skel/.bash_profile directly will prevent
# setup from updating it.
# The copy in your home directory (~/.bash_profile) is yours, please
# feel free to customise it to create a shell
# environment to your liking. If you feel a change
# would be benifitial to all, please feel free to send
# a patch to the cygwin mailing list.
# ~/.bash_profile: executed by bash for login shells.
# source the system wide bashrc if it exists
if [ -e /etc/bash.bashrc ] ; then
source /etc/bash.bashrc
fi
# source the users bashrc if it exists
if [ -e "${HOME}/.bashrc" ] ; then
source "${HOME}/.bashrc"
fi
# Set PATH so it includes user's private bin if it exists
# if [ -d "${HOME}/bin" ] ; then
# PATH=${HOME}/bin:${PATH}
# fi
# Set MANPATH so it includes users' private man if it exists
# if [ -d "${HOME}/man" ]; then
# MANPATH=${HOME}/man:${MANPATH}
# fi
# Set INFOPATH so it includes users' private info if it exists
# if [ -d "${HOME}/info" ]; then
# INFOPATH=${HOME}/info:${INFOPATH}
# fi
Here's my /etc/bash.bashrc
$ cat /etc/bash.bashrc
# To the extent possible under law, the author(s) have dedicated all
# copyright and related and neighboring rights to this software to the
# public domain worldwide. This software is distributed without any warranty.
# You should have received a copy of the CC0 Public Domain Dedication along
# with this software.
# If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
# base-files version 4.1-1
# /etc/bash.bashrc: executed by bash(1) for interactive shells.
# The latest version as installed by the Cygwin Setup program can
# always be found at /etc/defaults/etc/bash.bashrc
# Modifying /etc/bash.bashrc directly will prevent
# setup from updating it.
# System-wide bashrc file
# Check that we haven't already been sourced.
([[ -z ${CYG_SYS_BASHRC} ]] && CYG_SYS_BASHRC="1") || return
# If not running interactively, don't do anything
[[ "$-" != *i* ]] && return
# Set a default prompt of: user#host and current_directory
PS1='\[\e]0;\w\a\]\n\[\e[32m\]\u#\h \[\e[33m\]\w\[\e[0m\]\n\$ '
# Uncomment to use the terminal colours set in DIR_COLORS
# eval "$(dircolors -b /etc/DIR_COLORS)"
I don't modify $PATH in my $HOME/.bashrc anywhere other than the set PATH= command above.
If I prepend only one path to $PATH, that would get duplicated as well:
PATH="/cygdrive/c/Program Files/Java/jdk1.6.0_26/bin":$PATH
Results in:
Dragos#dragos ~
$ echo $PATH | tr ':' '\n'
/cygdrive/c/Program Files/Java/jdk1.6.0_26/bin
/cygdrive/c/Program Files/Java/jdk1.6.0_26/bin
/usr/local/bin
/usr/bin
/cygdrive/c/WINDOWS
/cygdrive/c/WINDOWS/system32
/cygdrive/c/WINDOWS/System32/Wbem
/cygdrive/c/curl
/
/cygdrive/c/gnupg
/cygdrive/c/Progra~1/cvsnt
/cygdrive/c/Progra~1/GNU/WinCvs 2.0
/cygdrive/c/Progra~1/Notepad++
/cygdrive/c/Progra~1/PuTTY
/cygdrive/c/Progra~1/WinSCP
/cygdrive/c/Python26
/cygdrive/c/Python26/Lib/site-packages/PyQt4/bin
/cygdrive/c/Python26/Scripts
/usr/bin
/usr/lib/lapack
So... Why the duplicates?
Addendum:
I found that I'm executing bash twice in my C:\cygwin\Cygwin.bat
The reason is that I have a context menu command to "Open Bash Here" that passes
a starting path to C:\cygwin\Cygwin.bat
Here's my C:\cygwin\Cygwin.bat
#echo off
C:
set PATH=%PATH%;C:\cygwin\bin
REM SHELL needed for any screen instances started from bash
set SHELL=/bin/bash
set HOME=C:\cygwin\home\Dragos
set HOMEDRIVE=C:
set HOMEPATH=\cygwin\home\Dragos
REM
if not [%1]==[] (
C:\cygwin\bin\cygpath %1 > tmpFile
set /p startingpath= < tmpFile
del tmpFile
)
if "%startingpath%"=="" start C:\cygwin\bin\mintty.exe --icon /Cygwin-Terminal.ico --size 140,50 --exec /bin/bash --login -c "exec /bin/bash -rcfile ~/.bashrc"
if not "%startingpath%"=="" start C:\cygwin\bin\mintty.exe --icon /Cygwin-Terminal.ico --size 140,50 --exec /bin/bash --login -c "cd '%startingpath%'; exec /bin/bash -rcfile ~/.bashrc"
exit
Addendum:
Figured out that I need to pass --noprofile --norc to bash when calling bash.
Here's the updated C:\cygwin\Cygwin.bat
#echo off
C:
set PATH=%PATH%;C:\cygwin\bin
REM SHELL needed for any screen instances started from bash
set SHELL=/bin/bash
set HOME=C:\cygwin\home\Dragos
set HOMEDRIVE=C:
set HOMEPATH=\cygwin\home\Dragos
REM
if not [%1]==[] (
C:\cygwin\bin\cygpath %1 > tmpFile
set /p startingpath= < tmpFile
del tmpFile
)
if "%startingpath%"=="" start C:\cygwin\bin\mintty.exe --icon /Cygwin-Terminal.ico --size 140,50 --exec /bin/bash --login
if not "%startingpath%"=="" start C:\cygwin\bin\mintty.exe --icon /Cygwin-Terminal.ico --size 140,50 --exec /bin/bash --noprofile --norc --login -c "cd '%startingpath%'; exec /bin/bash -rcfile ~/.bashrc"
exit
I don't have Cygwin installed, and I don't have a Windows machine, so I can't give you a boatload of details.
See if the man bash page can help you. In normal BASH, the /etc/profile, /etc/bashrc, the $HOME/.bash_profile, the $HOME/.bashrc, and sometimes the $HOME/.profile are all read in depending whether this is a login shell or not. Cygwin has it's own special versions of each of these files in the /etc directory. However, there's also other scripts that get invoked and can affect your Cygwin environment. For example, there are special scripts to import Windows environment variables including %PATH%.
In Cygwin, the default is to include the Windows %PATH% variable as part of the Cygwin path. It's actually a general import of all Windows environment variables (and depending upon the installation, the \ is sometimes converted to a / and short directory names are used).
If you open xterm windows and not standard Windows console windows for your Cygwin command line, you'll also have to check the xserve script (or whatever it's called) because that also imports a lot of stuff into the Cygwin environment.
I've used Cygwin in the past, and every time I use Cygwin, I find myself chasing down these exact things, plus a few other issues: For example, the default Kornshell load environment script has a bug in it. I believe they have a literal "^G" instead of a Ctrl-G, or maybe it was another control character. I can't remember. All I know is I spend about an hour or two cleaning up my Cygwin environment every time I install it. I like Cygwin, but it can be a pain.
Sorry I can't give you more specific directions.
Just set the PATH to whatever you like (without a reference to $PATH). You shouldn't trust the PATH that some random sysadmin thinks is a good PATH anyway. Do this in the file sourced last for your shell.

How to create a temporary directory?

I use to create a tempfile, delete it and recreate it as a directory:
temp=`tempfile`
rm -f $temp
# <breakpoint>
mkdir $temp
The problem is, when it runs to the <breakpoint>, there happens to be another program wants to do the same thing, which mkdir-ed a temp dir with the same name, will cause the failure of this program.
Use mktemp -d. It creates a temporary directory with a random name and makes sure that file doesn't already exist. You need to remember to delete the directory after using it though.
For a more robust solution i use something like the following. That way the temp dir will always be deleted after the script exits.
The cleanup function is executed on the EXIT signal. That guarantees that the cleanup function is always called, even if the script aborts somewhere.
#!/bin/bash
# the directory of the script
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# the temp directory used, within $DIR
# omit the -p parameter to create a temporal directory in the default location
WORK_DIR=`mktemp -d -p "$DIR"`
# check if tmp dir was created
if [[ ! "$WORK_DIR" || ! -d "$WORK_DIR" ]]; then
echo "Could not create temp dir"
exit 1
fi
# deletes the temp directory
function cleanup {
rm -rf "$WORK_DIR"
echo "Deleted temp working directory $WORK_DIR"
}
# register the cleanup function to be called on the EXIT signal
trap cleanup EXIT
# implementation of script starts here
...
Directory of bash script from here.
Bash traps.
My favorite one-liner for this is
cd $(mktemp -d)
The following snippet will safely create and then clean up a temporary directory.
The first trap line executes exit 1 command when any of the specified signals is received. The second trap line removes the $TEMPD on program's exit (both normal and abnormal). We initialize these traps after we check that mkdir -d succeeded to avoid accidentally executing the exit trap with $TEMPD in an unknown state.
#!/bin/bash
# set -x # un-comment to see what's going on when you run the script
# Create a temporary directory and store its name in a variable.
TEMPD=$(mktemp -d)
# Exit if the temp directory wasn't created successfully.
if [ ! -e "$TEMPD" ]; then
>&2 echo "Failed to create temp directory"
exit 1
fi
# Make sure the temp directory gets removed on script exit.
trap "exit 1" HUP INT PIPE QUIT TERM
trap 'rm -rf "$TEMPD"' EXIT
Here is a simple explanation about how to create a temp dir using templates.
Creates a temporary file or directory, safely, and prints its name.
TEMPLATE must contain at least 3 consecutive 'X's in last component.
If TEMPLATE is not specified, it will use tmp.XXXXXXXXXX
directories created are u+rwx, minus umask restrictions.
PARENT_DIR=./temp_dirs # (optional) specify a dir for your tempdirs
mkdir $PARENT_DIR
TEMPLATE_PREFIX='tmp' # prefix of your new tempdir template
TEMPLATE_RANDOM='XXXX' # Increase the Xs for more random characters
TEMPLATE=${PARENT_DIR}/${TEMPLATE_PREFIX}.${TEMPLATE_RANDOM}
# create the tempdir using your custom $TEMPLATE, which may include
# a path such as a parent dir, and assign the new path to a var
NEW_TEMP_DIR_PATH=$(mktemp -d $TEMPLATE)
echo $NEW_TEMP_DIR_PATH
# create the tempdir in parent dir, using default template
# 'tmp.XXXXXXXXXX' and assign the new path to a var
NEW_TEMP_DIR_PATH=$(mktemp -p $PARENT_DIR)
echo $NEW_TEMP_DIR_PATH
# create a tempdir in your systems default tmp path e.g. /tmp
# using the default template 'tmp.XXXXXXXXXX' and assign path to var
NEW_TEMP_DIR_PATH=$(mktemp -d)
echo $NEW_TEMP_DIR_PATH
# Do whatever you want with your generated temp dir and var holding its path
I need the following features:
Put all temp files into a single directory with a specific namespace for reusing.
Create temp files with filename prefix and suffix (extension).
With bash script on macOS:
$ namespace="com.namespace.mktemp"
# find directory for reusing
$ ls -d "${TMPDIR}${namespace}"*
# create directory if not exists
$ mktemp -d -t "$namespace"
/var/folders/s_/.../T/com.namespace.mktemp.HjqGT6w2
# create tempfile with directory name and file prefix
$ mktemp -t "com.namespace.mktemp.HjqGT6w2/file-prefix"
/var/folders/s_/.../T/com.namespace.mktemp.HjqGT6w2/file-prefix.sZDvjo14
# add suffix - `mktemp` on macOS does not support `--suffix`
mv "/var/folders/s_/.../file-prefix.sZDvjo14" "/var/folders/s_/.../file-prefix.sZDvjo14.txt"
The gmktemp (brew install coreutils) is a little different:
supports --suffix and --tmpdir
Xs are required in template and prefix
template should not contain directory, set TMPDIR instead
$ namespace="com.namespace.gmktemp"
# create directory if not exists
$ gmktemp -d -t "$namespace.XXXXXXXX"
/var/folders/s_/.../T/com.namespace.gmktemp.BjFtIAyZ
# set TMPDIR
TMPDIR="/var/folders/s_/.../T/com.namespace.gmktemp.BjFtIAyZ"
# create tempfile with directory name and file prefix
$ gmktemp --suffix=".txt" -t "prefix.XXXXXXXX"
/var/folders/s_/.../T/com.namespace.gmktemp.BjFtIAyZ/prefix.LWHj0G95.txt

Resources