1

I have a file called "data1.dat", I want to be able to use the file as an argument in my script without the .dat extension:

./myscript.sh data1

instead of

./myscript.sh data1.dat

is this possible, if so how would you do it?

  • In your script, after your sanity checks, something like myfile=${1}.dat, followed by references to $myfile? – DopeGhoti Feb 22 '16 at 19:58
2

Absolutely. You'll just need to do some text-processing of the input given--if it doesn't already end in .dat, you just add the .dat.

#! /bin/bash

if [[ $# -lt 1 ]]; then
    echo "Usage: $0 <datafile name>" >&2
    exit 1
fi

DATFILE="$1"

if [[ "$DATFILE" != *".dat" ]]; then
    DATFILE="${DATFILE}.dat"
fi

if [[ ! -r "$DATFILE" ]]; then
    echo "Error: Data file '${DATFILE}' does not exist." >&2
    exit 1
fi

echo "Using data file '${DATFILE}'..."
1

assumming extension is always .dat

filedat=$(dirname -- "$1")/$(basename -- "$1" .dat).dat

where

  • $1 is argument
  • $(dirname -- "$1") will pick dir name (dirname ../foo/bar/baz.dat ) => ../foo/bar
  • $(basename -- "$1" .dat) will trip optional .dat $(basename foo.dat .dat) => foo, $(basename foo .dat) => foo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.