Reading and tab-completing a directory name in a bash script - bash

I want to prompt the user for a directory name, and have them able to tab-complete to a valid directory.
So far, I've got tab-completion working for both files and directories using "read -e". I only want directories to be autocompleted when the user presses tab.
Here's what I have:
echo "Enter a directory"
read -e -p "> " DEST
How can I make bash only return a list of directories when the user presses tab, rather than a list of files and directories?

An alternate approach that gives you a lot of flexibility is to use compgen; see my answer here for details.

Here's my quick take at the problem. For some reason I had to actually use bash and not sh on my computer, due to the use of pushd and popd. I think it's well commented enough for me to not explain it any further.
#!/bin/sh
tempdir=`mktemp -d`
# save the current directory
pushd .
# make a new folder, then make a bunch of new directories
# mirroring those in our current directory
for i in $(find . -type d); do mkdir "$tempdir/$i" ; done
# change to the temporary directory
cd "$tempdir"
echo "Enter a directory"
read -e -p ">" DEST
echo "You told me $DEST"
# return to our original directory
popd
# clear out that temporary directory we made
rm -rf "$tempdir"
But Jacob's response is probably more efficient and cleaner than mine.

Related

mv: cannot stat [DIRECTORY/FILE]: no such file or directory

EDIT: DIR_trash="trash"
I wrote a function to move a file to current directory.
if [ "$1" == "-u" ]
then
if [ $# == 1 ]
then
echo "Something went wrong. Please make sure you're passing the name of the file/directory after '-u'."
else
if [ -f $DIR_trash/$2.zip ]
then
echo "$2.zip has been found in the trash."
cd
cd $DIR_trash
sed -i "/$2/d" $file7
mv -i /$DIR_trash/$2.zip .
unzip $2.zip
\rm $2.zip
cd
else
echo "$2.zip has not been found in the trash."
fi
fi
fi
As you can see, there is a line of code which says:
mv -i /DIR_trash/$2.zip .
So basically I'm trying to move a file that I passed in argument 2 to current directory, from trash. I always run this script from home directory, which does have trash directory. This is what I get when I run this:
Whenever I manually write this is in the Konsole (from home direcotry) it does work:
rm -u trash/d1 .
I'm out of ideas. Could anyone please help?
Let's say you run the script with the current directory being /some/where, and with the arguments -u and d1. I'll also assume that your home directory is /home/ninini. Let's look at where your script looks for files.
DIR_trash="trash"
if [ -f $DIR_trash/$2.zip ]
You check if /some/where/trash/d1.zip exists.
cd
cd $DIR_trash
Assuming both cd commands succeed, the current directory is now /home/ninini/trash.
mv -i /$DIR_trash/$2.zip .
You're saying to move /trash/d1.zip to the current directory, which is /home/ninini/trash.
Neither the source nor the destination make sense. The source /$DIR_trash doesn't make sense: why would you be looking for a directory called trash under the root directory? And the destination doesn't make sense since you just attempted to change to the trash directory, and now you're attempting to move a file out of the trash directory… into the trash directory.
I can't tell what the correct code is because you didn't say what the script is meant to do. You do say that you want to “to move a file to current directory”; then you must not change the current directory midway through the script! Assuming that the path $DIR_trash/$2.zip from the test command is the correct one, remove the cd commands and write
mv -i -- "$DIR_trash/$2.zip" .
Note that this moves the file from a directory called trash under the current directory. If this isn't what you wanted, you need to change the definition of DIR_trash. It should probably be an absolute path, perhaps
DIR_trash=~/trash
Note also that your script breaks on files containing whitespace and other special characters. Always put double quotes around variable substitutions: "$VAR", not $VAR. (Exception: when you know you need some effect that the double quotes prevent, and you understand why it's safe to leave them out.)

BASH Script for creating multiple directories, moving files, and then renaming said files

I am trying to make a bash script to create directories with the same name as each file in a given directory, then move said files to their respective directories, and then rename the files.
Basically - a quantum chemistry program that I use requires that the input files be named "ZMAT". So, if I have multiple jobs, I currently need to manually create directories, and then move the ZMAT files into them (can only run one job per folder).
When I run my code, I get "binary operator expected". I am not sure what this means. Some help please.
Here is what I have so far:
#!/bin/bash
if [ -e *.ZMAT ];
then
echo "CFOUR Job Detected"
for INPFILE in *.ZMAT; do
BASENAME=$(basename $INPFILE )
INPFILE=$BASENAME.ZMAT
OUTFILE=$BASENAME.out
XYZFILE=$BASENAME.xyz
ERRORFILE=$BASENAME.slu
if [ ! -e $ERRORFILE ];
then
# Create folder in scratch directory with the basename
mkdir /scratch/CFOUR/$BASENAME
# Move the file to its directory
mv -f $INPFILE /scratch/CFOUR/$BASENAME
# cd to the new directory
cd /scratch/CFOUR/$BASENAME
# Change the file name to just ZMAT
mv -f $INPFILE ZMAT
echo "Submitting CFOUR Job"
# Submit to scheduler
#RUN_COMMAND="sbatch -J $BASENAME _CFOUR_MRCC_SLURM.SUB"
#eval $RUN_COMMAND
else
echo "Error File Detected - Not Submitting Job"
fi
done
fi
An alternative would be to create symlinks to the original files.
As you said before, each ZMAT symlink would need to be in its own directory.
The upside is that the original data doesn't move, so less risk of breaking it, but the tool you want to use should read the symlinks as if they are the files it is looking for.
This one-liner creates an out directory in the current folder that you could subsequently move wherever you want it. You could easily create it where you do want it by replacing "out" with whatever absolute path you wanted
for i in *.ZMAT; do mkdir -p out/$i ; ln -s $PWD/$i out/$i/ZMAT ; done
I believe I have solved my problem. Here is the new script, which appears to be working fine. Any input is welcome though!
#!/bin/bash
SUBDIR=$(pwd)
for i in *.ZMAT; do
BASENAME=$(basename $i .ZMAT)
INPFILE=$BASENAME.ZMAT
OUTFILE=$BASENAME.out
XYZFILE=$BASENAME.xyz
ERRORFILE=$BASENAME.slu
if [ ! -e $ERRORFILE ];
then
mkdir /scratch/CFOUR/$BASENAME # Create Scratch Folder
cp $INPFILE /scratch/cdc/CFOUR/$BASENAME # Move Input to Scratch
cd /scratch/CFOUR/$BASENAME #cd to Scratch Folder
mv -f $INPFILE ZMAT # Change Input Name
echo "Submitting CFOUR Job"
# Submit to scheduler
#RUN_COMMAND="sbatch -J $BASENAME _CFOUR_MRCC_SLURM.SUB"
#eval $RUN_COMMAND
cd $SUBDIR #Go back to SUBDIR
else
echo "Error File Already Exists"
fi
done

How do I Batch Rename Folders in OSX?

So I have been trying to rename about 5000 folders based on a CSV (Old name, Newname)
This is a one time operation, once hdkjsh2-2f8c-46b9-bbdb_doc is converted to 3 then it will not need to be touched again.
I have tried the solution here (Setting up an automator workflow with a command script) but found that it does not do a great deal when it comes to folder/directory names and all the guides/documentation is around file names and not folder.
Any suggestions would be much appreciated
Example of CSV
Doc_Location, New_ID
hdkjsh2-2f8c-46b9-bbdb_doc , 3
Please make a backup before trying the following.
Save the following script in your HOME directory as renamer:
#!/bin/bash
cat "file.csv" | while IFS=' ,' read dir new ; do
if [ -d "$dir" ]; then
echo Rename $dir as $new
#mv "$dir" "$new"
else
echo "ERROR: Directory $dir not found - ignored"
fi
done
Then start Terminal and make the script executable by running:
chmod +x $HOME/renamer
Then change directory to where your directories are that need renaming:
cd path/to/things/needing/renaming
Make sure you have your CSV, called file.csv saved in that directory, then run with:
$HOME/renamer
It doesn't actually do anything, it just tells you what it would do. If it looks correct, edit $HOME/renamer and remove the single # on the line that says:
#mv "$dir" "$new"
so that is looks like:
mv "$dir" "$new"
Then be doubly sure you have made a backup and run the script again:
$HOME/renamer
Go to the folder where the other folders you want to rename are located. Select all the folders you want to rename. Then click on the action icon at the top of finder window. This will open a window where one option is to rename x items. See image below.
When you select "Rename x items" you get a box like the one shown below where you can specify the new names.

Shell Script to redirect to different directory and create a list file

src_dir="/export/home/destination"
list_file="client_list_file.txt"
file=".csv"
echo "src directory="$src_dir
echo "list_file="$list_file
echo "file="$file
cd /export/home/destination
touch $list_file
x=`ls *$file | sort >$list_file`
if [ -s $list_file ]
then
echo "List File is available, archiving now"
y=`tar -cvf mystuff.tar $list_file`
else
echo "List File is not available"
fi
The above script is working fine and it's supposed to create a list file of all .csv files and tar's it.
However I am trying to do it from a different directory while running the script, so it should go to the destination directory and makes a list file with all the .csv in destination directory and make a .tar from the list file(i.e archive the list file)
So i am not sure what to change
there are a lot of tricks in filename handling. the one thing you should know is file naming under POSIX sucks. commands like ls or find may not return the expected result(but 99% of the time they will). so here is what you have to do to get the list of files truely:
for file in $src_dir/*.csv; do
echo `basename $file` >> $src_dir/$list_file
done
tar cvf $src_dir/mystuff.tar $src_dir/$list_file
maybe you should learn bash in a serious manner and try to google first before you asking question in SO next time.
http://www.gnu.org/software/bash/manual/html_node/index.html#SEC_Contents
http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO.html

Bash script to safely create symlinks?

I'm trying to store all my profile configuration files (~/.xxx) in git. I'm pretty horrible at bash scripting but I imagine this will be pretty straight forward for you scripting gurus.
Basically, I'd like a script that will create symbolic links in my home directory to files in my repo. Twist is, I'd like it warn and prompt for overwrite if the symlink will be overwriting an actual file. It should also prompt if a sym link is going to be overwritten, but the target path is different.
I don't mind manually editing the script for each link I want to create. I'm more concerned with being able to quickly deploy new config scripts by running this script stored in my repo.
Any ideas?
The ln command is already conservative about erasing, so maybe the KISS approach is good enough for you:
ln -s git-stuff/home/.[!.]* .
If a file or link already exists, you'll get an error message and this link will be skipped.
If you want the files to have a different name in your repository, pass the -n option to ln so that it doesn't accidentally create a symlink in an existing subdirectory of that name:
ln -sn git-stuff/home/profile .profile
...
If you also want to have links in subdirectories of your home directory, cp -as reproduces the directory structure but creates symbolic links for regular files. With the -i option, it prompts if a target already exists.
cp -i -as git-stuff/home/.[!.]* .
(My answer assumes GNU ln and GNU cp, such as you'd find on Linux (and Cygwin) but usually not on other unices.)
The following has race conditions, but it is probably as safe as you can get without filesystem transactions:
# create a symlink at $dest pointing to $source
# not well tested
set -e # abort on errors
if [[ ( -h $dest && $(readlink -n "$dest") != $source ) || -f $dest || -d $dest ]]
then
read -p "Overwrite $dest? " answer
else
answer=y
fi
[[ $answer == y ]] && ln -s -n -f -v -- "$source" "$dest"

Resources