Hi I wrote a script for class that took one specific file as an input. Ideally, it should be able to take any file as an input. How do I do that? Someone suggested using $@ since is a global variable but I'm kinda confused on how to implement it.
I'm thinking...

$@=$1
$1=filename.txt

then use $@ where I input the file

Is this the way to go?

I'd appreciate any help...

$@ is a built in variable that holds all the command line arguments passed to your script. $1 is just the first command line argument. Here's a useless script that illustrates use of $@

# Usage: bash thisfile anyfile [anyfile...]
for fname in $@; do
  echo "Will cat $fname"
  cat $fname
  echo "============================"
  echo ""
done

$@ is a built in variable that holds all the command line arguments passed to your script. $1 is just the first command line argument. Here's a useless script that illustrates use of $@

# Usage: bash thisfile anyfile [anyfile...]
for fname in $@; do


That will break if any arguments contain whitespace. $@ is the same as $* ; use quotes:

for fname in "$@"; do
echo "Will cat $fname"
  cat $fname


That will break if $fname contains whitespace; use quotes:

cat "$fname"
echo "============================"
  echo ""
done

Thank you guys for your explanations. You did clarify the difference between $@ and $1 for me.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.