0

I am learning shell scripting, and I have written two scripts one that copies many files at once to a folder and if the folder does not exist it creates it, works like a charm! You may use it :D and the other one that moves them, I mean cuts and pastes :)

to copy:

#!/bin/bash

if [ ! -e "$2" ]
then
    mkdir $2
fi

if [ "$3" ]; then
    cp -rn $1/*.$3 $2
    echo "Copying *.$3 done!"
else
    cp -rn $1/*.* $2
    echo 'Copying done!'
fi

to move:

#!/bin/bash

if [ ! -e "$2" ]
then
    mkdir $2
fi

if [ $3 ]; then
    mv -i $1/*.$3 $2
    echo "Moving *.$3 done!"
else
    mv -i $1/*.* $2
    echo 'Moving done!'
fi

I would like to be able to use them like any other shell command (eg. ls, ping, cd...) everywhere in my system. How can I achieve that? Thanks!

3
  • 2
    Put the directory that contains them in your $PATH environment variable. Commented Nov 1, 2021 at 21:14
  • 1
    BTW, [ $3 ] should be [ "$3" ]. Similarly, mv -i $1/*.$3 $2 should be mv -i "$1"/*."$3" "$2" -- if you don't quote your expansions they're subject to word-splitting, so filenames or directories with spaces will misbehave badly. shellcheck.net will detect these issues automatically. Commented Nov 1, 2021 at 21:20
  • 1
    @Seven : Why is this tagged bash and zsh? Commented Nov 2, 2021 at 9:55

1 Answer 1

0

You need to

  1. Name each script file what you'd like to call it when you run it (without the extension), e.g. copymany and movemany
  2. Place the copymany and movemany files in a folder, perhaps ~/bin
  3. Add the folder to your $PATH environment variable, e.g. export PATH=$PATH:$HOME/bin, in your .bashrc or .zshrc
Sign up to request clarification or add additional context in comments.

5 Comments

Questions that have been asked and answered many times before should be closed as duplicative rather than answered again. See the Answer Well-Asked Questions section of How to Answer.
@user17242583 : What's the point in emphasizing without the extension? If the OP wants to use file extensions, let him do so. We don't want to teach style questions here, do we?
@user17242583 : Also, in the way you defined PATH, the ~ would not be expanded to the HOME directory (neither in bash nor in zsh).
@user1934428 - There are concrete practical reasons for that "stylistic" choice; see the essay talisman.org/~erlkonig/documents/… (which has long been linked by the #bash IRC channel factoid bot, being in line with consensus). Moreover, the OP asked how to be runnable "like ping" -- it's not named ping.elf. Someone coming from Windows might expect extensions to be ignored during search path evaluation but that's not the case here.
@user1934428: simply, I assumed the OP wanted to be able to run the command as though it were a normal command. Such a thing is very common among new developers, etc.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.