954,525 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

how to write a script that takes any file as an input? (Newbie)

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...

lu2lu
Newbie Poster
2 posts since Feb 2011
Reputation Points: 10
Solved Threads: 0
 

$@ 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
griswolf
Veteran Poster
1,165 posts since Apr 2010
Reputation Points: 344
Solved Threads: 256
 

$@ 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

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

for fname in "$@"; do

[/indent]

echo "Will cat $fname"
  cat $fname

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

cat "$fname"

[/indent]

echo "============================"
  echo ""
done
cfajohnson
Junior Poster
196 posts since Dec 2008
Reputation Points: 25
Solved Threads: 23
 

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

lu2lu
Newbie Poster
2 posts since Feb 2011
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: