Linux arguments from file

How can I pass a file argument to my bash script using a Terminal command in Linux? [duplicate]

So my question is how can I pass a file argument to my bash script using a Terminal command in Linux? At the moment I’m trying to make a program in bash that can take a file argument from the Terminal and use it as a variable in my program. For example I run myprogram —file=/path/to/file in Terminal.

My Program

How can I achieve this with my program?

4 Answers 4

It’ll be easier (and more «proper», see below) if you just run your script as

Then you can access the path within the script as $1 (for argument #1, similarly $2 is argument #2, etc.)

If you want to extract the path from something like —file=/path/to/file , that’s usually done with the getopts shell function. But that’s more complicated than just referencing $1 , and besides, switches like —file= are intended to be optional. I’m guessing your script requires a file name to be provided, so it doesn’t make sense to pass it in an option.

you can use getopt to handle parameters in your bash script. there are not many explanations for getopt out there. here is an example:

links dead. here from internet archive:

Bash supports a concept called «Positional Parameters». These positional parameters represent arguments that are specified on the command line when a Bash script is invoked.

Positional parameters are referred to by the names $0 , $1 , $2 . and so on. $0 is the name of the script itself, $1 is the first argument to the script, $2 the second, etc. $* represents all of the positional parameters, except for $0 (i.e. starting with $1 ).

Assuming you do as David Zaslavsky suggests, so that the first argument simply is the program to run (no option-parsing required), you’re dealing with the question of how to pass arguments 2 and on to your external program. Here’s a convenient way:

The shift will remove the first argument, renaming the rest ( $2 becomes $1, and so on). $@` refers to the arguments, as an array of words (it must be quoted!).

If you must have your —file syntax (for example, if there’s a default program to run, so the user doesn’t necessarily have to supply one), just replace ext_program=»$1″ with whatever parsing of $1 you need to do, perhaps using getopt or getopts.

Читайте также:  Пропала иконка установки windows 10

If you want to roll your own, for just the one specific case, you could do something like this:

Источник

Pass content from .txt file as argument for bash script?

I need to «Write a script to add users to your system in which the names of the users are given to script as an argument n (in?, spell error by professor) a text file of the format

(rest of instructions FYI) Your script should create unique user names of up to 8 characters, and generate random passwords for the users. The users should be assigned home directories depending on the group they are in. You can assume that the users will belong to Management (“mgmt”), Employee (“empl”) or Temporary (“temp”) and that their respective directories are under these group names in /home. For e.g., if John Doe is in “mgmt.”, and his user name is jdoe1234, then his home directory should be in /home/mgmt/jdoe1234. Lock the home directories such that no one else has permissions to the home directories than the users themselves. Your script should generate a file called users.txt that contains the following columns:

Last Name First Name UID Password

which can be used to distribute the user names and passwords to the users.

The first part (not in italics) is what confuses me. If I understand his wording correctly, he wants me to take text from a separate .txt file and use it as the arguments for my script? With the idea of

except those args are going to be the first four words in the .txt file? Say, if the .txt file contains «Doe John A empl», then it would be like typing

Here’s my attempt so far (I’ve actually tried other things but this is what I have on screen right now, sort of what I started out with):

As of right now, anything below the first line doesn’t do anything. I got the first line from command line arguments from a file content and I used it because I thought it would let me use the content from a .txt file as arguments but it’s clearly not doing that. It’s just outputting the content of it, not using letting me using each word as an argument. Not sure what to do. Any help? I thought this wasn’t going to be very difficult as I started writing the script assuming the user would provide the arguments but I reread the first part of the instructions and assume he wants them to be taken from a separate .txt file.

Источник

How to use file contents as command-line arguments?

I’d like to use arguments from file as command-line arguments for some commands like gcc or ls.

For example gcc -o output -Wall -Werro

as file consist of:

Used for gcc command-line call.

6 Answers 6

Some programs use the «@» semantics to feed in args from a file eg. gcc @argfile

Читайте также:  Iso linux mint mate

Where, for gcc, argfile contains options

This can be nested so that argfile can contain

You can use xargs :

Edit: I’ve been downvoted because Laurent doesn’t know how xargs works, so here’s the proof:

The -t flag causes the command to be written to stderr before executing.

I recommend using $() along with cat:

The nice thing about $() over backticks (the classic way) is that it is easier to nest one within another:

Most of the time, command substitution (either through backticks or $(), as others have pointed out) is fine, but beware of shell expansion rules. Especially, keep in mind that unquoting is done before and word splitting is done after command substitution.

This is not too bad if all your arguments are words but if you start putting spaces or other special characters that would normally need to be quoted into your arguments, then you may meet with strange results (notice the abnormal spacing and quotes in the output):

Quoting the whole command subtitution is not a solution, obviously, as it would prevent word splitting (hence, your whole file’s content would appear as one long argument instead of many options), and would do nothing about the quotes.

One solution around this is to use the eval builtin:

Источник

How to pass command line parameters from a file

I have a C program that reads command line arguments from argv. Is it possible to make a pipe to redirect the contents of a file as command line arguments to my program? Suppose I have a file arguments.dat with this content:

And I want my program to be called with:

I tried the following:

3 Answers 3

xargs is your answer:

Check the manual for the many ways to customize xargs . For example, you can read line-by-line rather than by word, and you can use the arguments in more complex replacements.

With most shells, you can insert the contents of a file into a command line with $( :

If your shell doesn’t support that, then one of the older ways will work:

(You do know the difference between command line arguments and file input, right? Why would you expect to pipe command line arguments into a program?)

If You Don’t Want Arguments To Be Silently Split

. which is to say: The below answers apply to cases where it wouldn’t be acceptable for ./myprogram —first-argument «first value» to be silently changed into ./myprogram —first-argument; ./myprogram «first value» .

If your arguments are one-to-a-line literals

That is, if your input looks like:

and you mean this to run:

. then you should use (with bash 4.0 or later):

. or (for bash 3.x as well):

If your arguments are provided with quotes or escaping to distinguish them

That is, if your file contains something like (note that newlines and unquoted spaces behave identically here):

. and you mean this to run:

. then you should use:

If you control your argument format

Use NUL-delimited values. That is, create the file as so:

Читайте также:  Wireless windows 2012 server

. and parse it as follows:

This will work with all possible argument values, even ones with literal newlines, literal quotes, literal backslashes, or other nonprintable characters. (Literal NULs are not possible in UNIX command lines, since command lines are composed of NUL-terminated strings; thus, NUL is the only character which is completely safe to use to unambiguously separate arguments in a string).

If Splitting Arguments Across Invocations Is Desired

This subsection is relevant if the desired result (when there are more arguments in your file than can be passed to an invocation of your program) is multiple distinct invocations of the program, each one receiving a subset of arguments. This is a family of cases where xargs is the right tool for the job.

If on a GNU platform, you may want to run xargs -a arguments.dat instead of redirecting stdin; however, this isn’t supported with BSD xargs (as on MacOS), and so is not demonstrated here.

If your arguments are one-to-a-line literals

With GNU xargs (most Linux platforms):

With BSD xargs (MacOS, FreeBSD/OpenBSD/etc):

Источник

using linux how can I pass the contents of a file as a parameter to an executable?

let’s say I want to run ./program with a string argument

instead of typing ./program string each time, how can I do ./program where is a file that contains string?

6 Answers 6

This should do the trick:

If you want the entire file content in a single argument, add double quotation (tested in bash. I think It may vary shell to shell) :

Command

Explanation

$(cmd) runs a command and converts its output into a string. $(cmd) can also be written with backticks as `cmd` . I prefer the newer $(cmd) as it nests better than the old school backticks.

The command we want is cat file . And then from the bash man page:

The command substitution $(cat file) can be replaced by the equivalent but faster $( .

The quotes around it make sure that whitespace is preserved, just in case you have spaces or newlines inside of your file. Properly quoting things in shell scripts is a skill that is sorely lacking. Quoting variables and command substitutions is a good habit to good into so you don’t get bit later when your file names or variable values have spaces or control characters or other weirdnesses.

You can use one of:

The latter is useful if there may be multiple words in the file and you want them to be treated as a single argument. In any case, I prefer the use if $() to backticks simply due to it’s ability to nest (which is probably not a requirement in this case).

Also keep in mind that this answer (and others) are more related to the shell in use rather than Linux itself. Since the predominant and the best 🙂 shell seems to be bash , I’ve coded specifically for that.

Источник

Оцените статью