1

Usually when I use file names within a script I mention the filename explicitly within the script, for example as shown below,

#!/bin/bash ... echo "<dynamic text>" >> process_log.log ...

I was wondering if it is possible to pass filename to script like the following:

./script_name.sh file_1 file_2 file_3

with tab auto-complete functionality. (This would be very convenient !)

Does anybody has experience with this. Thank you.


read is one way to ask some input data but I feel it is cumbersome for multiple inputs and for long text.

2
  • Both are possible - passing filenames, using your example, you'd use $1, $2 and $3 to read the filenames inside your script. For auto-completion, complete will do it. If that (starts to) answer your question I'll write up a more detailed answer.
    – John N
    Dec 16, 2016 at 16:50
  • Thanks. Yeah that is what I am looking for, Please give details. :-)
    – ankit7540
    Dec 16, 2016 at 16:52

1 Answer 1

2

OK, this script takes one mandatory argument, and two optional arguments. It'll exit (with an error) if you don't specify at least one argument. It doesn't do much besides that!

#!/bin/sh
if [ -z "$1" ]
then
    echo "Missing filename: 1"
    exit 1
else
    file1=$1
fi
file2="$2"
file3="$3"
printf "File 1: %s\n" "$file1"
printf "File 2: %s\n" "$file2"
printf "File 3: %s\n" "$file3"
cat "$file1"

Save it as (for example) script_name.sh and set it to be an executable:

chmod u+x script_name.sh

Then run it like this:

./script_name.sh script_name.sh script_name.sh script_name.sh

It should display the three arguments you passed it (which are all "script_name.sh"), and then cat itself.

When I tried this, I experimented with tab completion - it worked fine automatically (it showed files and directories when I pressed Tab). I didn't do anything to make it do this. However, if you wanted to only let your script work with certain files complete -f -X '!*.png' script_name.sh - that'll only show ".png" files when you press Tab.

Edit to add:

complete isn't run from the script itself (script_name.sh in the example above). Create a separate file (completion_for_script_name.sh, for example):

complete -f -X '!*.png' script_name.sh

Use source to load the completion into the current environment:

source ./completion_for_script_name.sh

Typically, you'd do this in your shell's profile, e.g. .bash_profile or .bashrc.

3
  • Would be great to see an example of complete in action, i.e. where to put it in the script
    – Jortstek
    Nov 26, 2021 at 22:22
  • @Jorstek - thanks, that's a good point. Does my edit fully address it?
    – John N
    Nov 29, 2021 at 10:41
  • It does. Much appreciated.
    – Jortstek
    Nov 29, 2021 at 19:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .