Linux argument from file

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.

Источник

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.

Читайте также:  Babytype для windows 10

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.

Источник

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:

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

Читайте также:  D402 модем драйвер windows 10

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

With GNU xargs (most Linux platforms):

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

Источник

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.

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

Источник

How do I use the lines of a file as arguments of a command?

Say, I have a file foo.txt specifying N arguments

which I need to pass to the command my_command

How do I use the lines of a file as arguments of a command?

11 Answers 11

If your shell is bash (amongst others), a shortcut for $(cat afile) is $( , so you’d write:

Documented in the bash man page in the ‘Command Substitution’ section.

Alterately, have your command read from stdin, so: mycommand

As already mentioned, you can use the backticks or $(cat filename) .

What was not mentioned, and I think is important to note, is that you must remember that the shell will break apart the contents of that file according to whitespace, giving each «word» it finds to your command as an argument. And while you may be able to enclose a command-line argument in quotes so that it can contain whitespace, escape sequences, etc., reading from the file will not do the same thing. For example, if your file contains:

the arguments you will get are:

If you want to pull each line as an argument, use the while/read/do construct:

Читайте также:  Пропали данные с флешки после установки windows

will pass file contents to the command on stdin, but will strip newlines, meaning you couldn’t iterate over each line individually. For that you could write a script with a ‘for’ loop:

Or (the multi-line variant):

Or (multi-line variant with $() instead of « ):

References:

You do that using backticks:

If you want to do this in a robust way that works for every possible command line argument (values with spaces, values with newlines, values with literal quote characters, non-printable values, values with glob characters, etc), it gets a bit more interesting.

To write to a file, given an array of arguments:

. replace with «argument one» , «argument two» , etc. as appropriate.

To read from that file and use its contents (in bash, ksh93, or another recent shell with arrays):

To read from that file and use its contents (in a shell without arrays; note that this will overwrite your local command-line argument list, and is thus best done inside of a function, such that you’re overwriting the function’s arguments and not the global list):

Note that -d (allowing a different end-of-line delimiter to be used) is a non-POSIX extension, and a shell without arrays may also not support it. Should that be the case, you may need to use a non-shell language to transform the NUL-delimited content into an eval -safe form:

Here’s how I pass contents of a file as an argument to a command:

If all you need to do is to turn file arguments.txt with contents

into my_command arg1 arg2 argN then you can simply use xargs :

You can put additional static arguments in the xargs call, like xargs -a arguments.txt my_command staticArg which will call my_command staticArg arg1 arg2 argN

I suggest using:

Simply trim the end-line characters and replace them with spaces, and then push the resulting string as possible separate arguments with echo.

In my bash shell the following worked like a charm:

where input_file is

As evident, this allows you to execute multiple commands with each line from input_file, a nice little trick I learned here.

None of the answers seemed to work for me or were too complicated. Luckily, it’s not complicated with xargs (Tested on Ubuntu 20.04).

This works with each arg on a separate line in the file as the OP mentions and was what I needed as well.

One thing to note is that it doesn’t seem to work with aliased commands.

The accepted answer works if the command accepts multiple args wrapped in a string. In my case using (Neo)Vim it does not and the args are all stuck together.

xargs does it properly and actually gives you separate arguments supplied to the command.

After editing @Wesley Rice’s answer a couple times, I decided my changes were just getting too big to continue changing his answer instead of writing my own. So, I decided I need to write my own!

Read each line of a file in and operate on it line-by-line like this:

This comes directly from author Vivek Gite here: https://www.cyberciti.biz/faq/unix-howto-read-line-by-line-from-file/. He gets the credit!

Syntax: Read file line by line on a Bash Unix & Linux shell:
1. The syntax is as follows for bash, ksh, zsh, and all other shells to read a file line by line
2. while read -r line; do COMMAND; done
3. The -r option passed to read command prevents backslash escapes from being interpreted.
4. Add IFS= option before read command to prevent leading/trailing whitespace from being trimmed —
5. while IFS= read -r line; do COMMAND_on $line; done

And now to answer this now-closed question which I also had: Is it possible to `git add` a list of files from a file? — here’s my answer:

Источник

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