Tag Info

New answers tagged

0

First, move the existing executable to a new location: mv ./executable ./executable.original Second, create a shell script in it place. Place the following commands in a new file called ./executable: #!/bin/sh LD_PRELOAD=/some/lib ./executable.original my_arg1 my_argn "$@" some_other_command The shell will replace the incantation "$@" with arg1 arg2 ...


1

Cron jobs can be run as root or another specified user. If that user does not have the permission to write to the .sql file the job will fail. If the file exist and it has write permission for the user running the job the file will be written. if the file does not exist and the user does not have permission to create files in target directory, the job will ...


0

If your number 4 is place always on 5th field then with awk you can add newline it: $ awk 'BEGIN{FS=OFS="|"}$5="\n"$5' file John|freshman|seatle|math| 4|fulltime Bob|senior|Tacoma|biology| 4|part-time


1

You could use sed: sed -i 's/|4|/|\n4|/' file.txt This will replace |4| with |\n4| (i.e. a vertical bar, a newline, and then 4|).


0

As you noted, the problem was that a pipe to read is run in a subshell. One answer is to use a heredoc: numbers="01 02" read first second <<INPUT $numbers INPUT echo $first echo $second This method is nice in that it will behave the same way in any POSIX-like shell.


3

Some shells have the feature built-in. zsh zsh's =(...) form of process substitution uses a temporary file. For instance =(echo test) expands to the path of a temporary file that contains test\n. $ {cat $file; ls -l /dev/fd/3; echo test2 >&3; cat $file} 3<> ${file::==(echo test)} test lrwx------ 1 stephane stephane 64 Jan 30 11:19 /dev/fd/3 ...


1

I run FBSD myself. There was a post about this problem elsewhere too. I found that starting the script with the following greatly improves cross OS compatibility: #!/usr/bin/env bash


0

So this is your script: #!/bin/sh if [ ! -d "/opt/ftp/$PAM_USER" ]; then /usr/bin/env mkdir /opt/ftp/$PAM_USER /usr/bin/env chown ftp:ftp /opt/ftp/$PAM_USER fi Try your script with this: #!/bin/sh if [ ! -d "/opt/ftp/${PAM_USER}" ]; then /usr/bin/env mkdir /opt/ftp/${PAM_USER} /usr/bin/env chown ftp:ftp /opt/ftp/${PAM_USER} fi PAM_USER is a ...


5

If you're on system which has mktemp, you should use it as other answers. With POSIX toolchest: umask 0177 tmpfile=/tmp/"$0"."$$"."$(awk 'BEGIN {srand();printf "%d\n", rand() * 10^10}')" trap 'rm -f -- "$tmpfile"' INT TERM HUP EXIT : > "$tmpfile"


2

Use mktemp to create a temporary file or directory: temp_file=$(mktemp) Or for a direcotry: temp_dir=$(mktemp -d) At the end of the script you have to delete the temporary file/dir: rm ${temp_file} rm -R ${temp_dir} mktemp creates file in the /tmp directory or in the drectory given with the --tmpdir argument.


9

tmpfile=$(mktemp /tmp/abc-script.XXXXXX) : ... rm "$tmpfile" You can make sure that a file is deleted when the scripts exits (including kills and crashes) by opening a file descriptor to the file and deleting it. The file keeps available (for the script; not really for other processes but /proc/$PID/fd/$FD is a work-around) as long as the file descriptor ...


4

(this is not really an answer, more of a comment) You have to be a bit careful about the a && b || c shortcuts: if a returns success, then b is executed if b subsequently returns an exit status, then c will be executed too. $ [[ -f /etc/passwd ]] && { echo "file exists"; false; } || echo "file does not exist" file exists file does not ...


5

Assuming you want to use A && B || C, then simply call the function directly: tst && echo "success" || echo "failure" If you want to use [[, you'd have to use the exit value: tst if [[ $? -eq 0 ]] then ...


2

Your code is quite ok, I'd probably do that as a quick solution. It's more efficient to actually exit sed immediately after printing: sed -n '1{p;q}' to avoid reading the entire file for no reason. Now the most awkward part is reading the file twice to get first two lines. You could simply use shell builtins: { read -r var1; read -r var2; } < infile ...


4

You can use this command: awk '{print $1}' filename > newfile where filename is the name of the original big file and newfileis the file that will get the results.


0

It looks to me that var1 and var2 will get same value. I would use var1=$(awk 'NR==1' infile) var2=$(awk 'NR==2' infile) sed -i '1,2d' infile where NR is an awk variable meaning Number of Record, that is the line number. NR==1 select line 1 default awk action is to print the whole line


0

The problem is that running the script as nohup sh /path/to/your/script.sh overrides the shebang line interpreter. When called as sh then bash turns off certain features (that is probably similar with other shells) and thus cannot parse process substitution any more. The solution is to make sure that bash is running without restrictions. This can be done by ...


1

It all depends on what you want. If you want to process files one after the other, you can simply call your awk script on both files sequentially with a loop, and redirect the output: (for file in outfile1.out outfile2.out; do awk -f awk_file.awk < "$file"; done) > text_file.txt or in this case of two files, simply (awk -f awk_file.awk < ...


1

From wget manual: ‘--user=user’ ‘--password=password’ Specify the username user and password password for both FTP and HTTP file retrieval. These parameters can be overridden using the ‘--ftp-user’ and ‘--ftp-password’ options for FTP connections and the ‘--http-user’ and ‘--http-password’ options for HTTP connections. So what you ...


1

The other problem you had was that you also had extra quotes on the mv line. When you are using echo to print a command that will be copied to a shell you need quote everything twice, once for this shell, and once for the second. your echo mv worked fine as long as the filename did not begin with a dash or contain a single quote. The mv only needed quoted ...


3

You should never install files into home directories with packages. Instead, you can install default configuration files to /etc/skel so that new users created after your package is installed will have these files copied to their newly created home directories. Users that already exist will not get these new files though. Your application can create config ...


0

~, means the users folder which ever username the user has. But I strongly reccomend that you use /tmp instead, there is no reason to use ~.


0

This is VERY UNSECURE! But for your own risk: su have no but sudo have such option -S, --stdin Write the prompt to the standard error and read the password from the standard input instead of using the terminal device. The password must be followed by a newline character.


3

Basic example of sed usage using this as test.txt: one two three two four two five To replace two with foo in that file: sed -i 's/foo/two/g' test.txt What that means: sed is the name of the command, you'll find lots of tutorials (e.g.) and other documentation online, in addition to man sed. -i means edit a file in place. 's/foo/two/g': the s ...


-2

You just need to treat filename adding an escape caracter \ before the space. filename=$(echo $i|sed 's/ /\\ /g') mv $filename $new_filename


5

The main problem is that you loop over output of ls command. Use glob * instead: #!/bin/sh cd ~/Data for i in *; do echo "$i" filename="$i" date=$(date -n +%Y-%m-%d) new_filename="${date}${filename}" echo mv "${filename}" "${new_filename}" mv -- "${filename}" "${new_filename}" done Additionally I added -- to mv in order to treat ...


1

Arrays are defined differently: components=(Persistence Instrument "Accessory Engine") or components=(Persistence Instrument Accessory\ Engine) And accessed differently: for i in "${components[@]}"


6

Associative array in bash (and in other languages) does not preserve the order of elements in declaration. You can add another associative array to keep track the order of declaration: YELLOW=$'\e[93m' declare -A OP=( [Description]="remote to destination" [Source]="/var/www" [Destination]="/foo/bar" ...


1

var=$( cat foo.txt ) would store the output of the cat in variable var. var=$( ./myscript ) would store the output of myscript in the same variable.


0

Assuming that an extension starts with a letter after the period, the following command prints .tar.gz: echo gbamidi-v1.0.tar.gz | awk \ 'BEGIN { FS = "\." } \ { \ extension = ""; \ i = NF; \ while ((i > 1) && (substr($i, 1, 1) ~ /[A-Za-z]/)) { \ extension = "." $i extension; \ i-- \ ...


0

This may not be valid in all cases, but .gz is the extension. foo.tar.gz first has to be extracted to a foo.tar, then unarchived. The fact you can do that in one command is just convenience. You need to get the extension? It's .gz. If you need something else then you're going to need to target specific things using regex, awk, cut or the like.


1

Hmm... Seems like you could take better advantage of the --format argument here to use --printf instead and just pass the lot over a pipe. Also, your if...fi is a compound command - it can take a redirect which all contained commands will inherit, so maybe you don't need to nest the heredoc at all. if [ "$diffLines" = 1 ] then stat --printf "Last ...


0

The other method would be herestrings: mail_content="Last Change: $dateLastChanged This is an automated warning of stale data for the UNC-G Blackboard Snapshot process." mailx -r "Systems and Operations <sysadmin@[redacted].edu>" -s "Warning Stale BB Data" jadavis6@[redacted].edu <<<"$mail_content"


2

As a non-regex alternative, use pup: pup 'a[href] attr{href}' < yourfile.html Will find all a elements that have a href attribute, then display the value of the href attribute. To install pup, you need Go (a programming language): sudo apt-get install golang sudo go get github.com/ericchiang/pup The advantage of this solution is that it doesn't ...


0

wget -qO- google.com | tr \" \\n | grep https\*:// ...would probably do pretty well. As written, it prints: http://schema.org/WebPage http://www.google.com/imghp?hl=en&tab=wi http://maps.google.com/maps?hl=en&tab=wl https://play.google.com/?hl=en&tab=w8 http://www.youtube.com/?tab=w1 http://news.google.com/nwshp?hl=en&tab=wn ...


5

As I said in my comment, it's generally not a good idea to parse HTML with Regular Expressions, but you can sometimes get away with it if the HTML you're parsing is well-behaved. In order to only get URLs that are in the href attribute of <a> elements, I find it easiest to do it in multiple stages. From your comments, it looks like you only want the ...


2

Not sure if you are limited on tools: But regex might not be the best way to go as mentioned, but here is an example that I put together: cat urls.html | grep -Eo "(http|https)://[a-zA-Z0-9./?=_-]*" | sort | uniq grep -E : is the same as egrep grep -o : only outputs what has been grepped (http|https) : is an either / or a-z : is all lower case A-Z : is ...


4

If your grep supports Perl regexes: grep -Po '(?<=href=")[^"]*(?=")' (?<=href=") and (?=") are lookaround expressions for the href attribute. This needs the -P option. -o prints the matching text. For example: $ curl -sL https://www.google.com | grep -Po '(?<=href=")[^"]*(?=")' /search? https://www.google.co.in/imghp?hl=en&tab=wi ...


0

Assuming you have to permissions to (or can convince your SysAdmin), I suggest looking into tmux which is a terminal multiplexer. Tmux allows you to do everything you are talking about and more. You can have it manage all your windows and just detach your session when done. Picking up were you left off is as easy as reattaching to your detached session (one ...


-1

Create the string as a variable and pass that variable to curl. string="${WEBSITE_URL}/ACTION_NAME/ACTION1;id=${ID}?Command=TEST&id1=${ID1}&id2=${ID2}&id3=${ID3}" echo $string #this should get the right string to be passed to curl curl -X GET $string


0

bash uses all characters after $ which are valid in a variable name to determine the name i.e. the first illegal char limits the name string. In case of doubt ${Variable} should be used. You already mention that so your problem must be something different.


1

If you have to cd in and out of several directories then it makes sense to use cd - instead which takes you to the last current working directory. Or you use pushd / popd (in bash). for directory in *; do pushd "$directory" index=1 for filename in *; do extension="${filename##*.}" if [ "$filename" != "$extension" ]; then ...


2

If you're jailing the user, you should probably just give him a copy of the script. If you set him up with a chrooted account, he wouldn't see anything outside of his home directory.


0

There are two ways that you can do this. 1: Using sudo One is to allow everyone to use sudo to mount the disk. The sudo line should look like this: ALL ALL = NOPASSWD: mount /dev/sda1 /media/kiancross/MinecraftServer The first ALL means "all users"; the second means "on any server where this sudoers file is installed". You also need to have the full ...


1

As indicated in the comment to the question man rsnapshot says: EXIT VALUES 0 All operations completed successfully 1 A fatal error occurred 2 Some warnings occurred, but the backup still finished So you can modify your command line for example: rsnapshot ... with_all_arguments ; [ $? == 0 ] && rm -f flag.file || ...


2

When you type function_under_test, the shell think it's a command, not a variable. You need to expand it, so function_uneder_test will be expanded to sum_squares. Change your line 32 to: "$function_under_test" "$3"


3

You seem to be doing things in a needlessly complicated way. Why not just dpkg -l curl || apt-get -y -qq install curl > /dev/null 2>&1 You did ask for a one-liner after all. Since, presumably, all you want is to know whether curl is available, you could also just do type curl >/dev/null 2>&1 || apt-get -y -qq install curl


0

There's no point to checking if a package is installed and installing if not. Either: You check for what you want from the package, like the curl binary: command -v curl, so that the user can provide alternatives if they feel like it. You check if a particular version of what you wanted is installed, using something like apt-cache policy. If neither case ...


2

There are two bugs in your code, one serious the other not so much: You are using backticks twice. Also don't use backticks. Use command substitution as the following: $(command ...) query=$(dpkg-query -W -f '${Status}') Query will already contain the result of the command call. When you now execute `$query` you will now try to execute the result, ...


0

If the script needs to access the history, insert an alias into the .bashrc. I have this for the command auto which has an option to repeat the latest command, ad infinitum, depending on changes in the provided commandline arguments. The alias: auto = 'history | auto' Assuming that some_command_to_test depends on input.py and output.py I use this to ...



Top 50 recent answers are included