Hot answers tagged

10

The messages you mention are not printed to standard output but to standard error. So, to capture them, you either need to redirect standard error instead of standard output: sudo -u user bash -c "git clone https://github.com/foo.git ~/foo 2>> log" Or both STDERR and STDOUT: sudo -u user bash -c "git clone https://github.com/foo.git ~/foo >> ...


9

You provided a line with 6 "words", yet you're reading them into three variables: a, b, and c. The first variable a is assigned 1, the second variable b is assigned 2, and c gets to hold the rest of the line: "3 4 5 6". The output is 3 4 5 6 b a because you didn't write $c $b $a, but only $c b a. If you had written $c $b $a, the result would have been 3 4 ...


7

The syntax for a for loop is like this: for x in {list} do command... command... done There is neither do nor done on any of your loops. Bash Guide for Beginners and Advanced Bash Scripting Guide are good references on syntax and best scripting practices.


4

ShellCheck is a good start for bash programming. It gives quite useful hints: Line 6: if [[ "$CDTRACK" =~ "([[:alpha:][:blank:]]*)- ([[:digit:]]*) - (.*)$" ]] ^-- SC2076: Don't quote rhs of =~, it'll match literally rather than as a regex. Regex can't be quoted like this. Working example with escaped special characters (basically ...


3

The variable assignments could be simplified as follows: if [ ! -n "${varname}" ]; then varname="some default" fi is equivalent to varname=${varname:-"some default"} and, even more terse, : ${varname:="some default"} To parametrize this for arbitrary variable names and default values, I suggest to define a function. bash insists on an explicit ...


2

Came looking for a one-liner on MacOS. Settled on the following. Compiled and added this tool to my path. This took less then 30 seconds. $ git clone git@github.com:sschober/kqwait.git $ cd kqwait $ make $ mv kqwait ~/bin $ chmod +x ~/bin/kqwait Next, I went to the directory in which I wished to do the watching. In this case, I wished to watch a markdown ...


2

Use "printf" to escape strings If I understand this correctly, you're creating a variable assignment statement which will be concatenated with a script file, and everything will be executed in a shell. In this case, I suggest something along the lines of: #!/bin/bash my_script=$(<somescript.sh) cont=$(<file) var='xx' # This will escape the string ...


2

Where is "n"? You write: sd = sqrt(ss/n) but where in your code did you assign the variable "n"? The way awk sees it, "n" is zero. Also, where is column 5 in a=$5 (and, third issue, why is this assignment in the END section)? Your example contains only 4 columns.


2

expr1; expr2; expr3 is not an arithmetic expression since ; is not a possible operator in arithmetic expressions, as you can see by reading the syntax of arithmetic expressions in the bash manual. The syntax of for loops gives the form for ((expr1; expr2; expr3)) ; do commands ; done, with the semicolons. So the ((…)) bit is not the same thing as an ...


2

The reason this doesn't work can be inferred from the error message (that you omitted to provide): sed: -e expression #1, char 14: unterminated `s' command The sed command does not accept a multi-line value. You have to collapse your multiple lines into a single line. You could do this with a script such as this: #!/bin/ksh S_ids="'$(cut -d'|' -f1 ...


2

Your format string to date is wrong. %I gives the hour in 12 hour format (01..12), you probably want %M, and then your command seems to work (on this linux box - I don't have a synology to try on).


2

Yes, It's possible [[ "a" == "a" ]] && echo true || echo false Try replacing "a" with "b", to see false: [[ "b" == "a" ]] && echo true || echo false


2

Maybe you actually want: while IFS='|' read -r i j rest <&3; do { printf '%s\n' "something with $i and $j" } 3<&- done 3< "$INPUTFILE" But using a shell loop to process text is often the wrong way to go. Here, it sounds like you just need: awk -F '|' '{print $1 ":" $2}' < "$INPUTFILE" Now as an answer to the question in the ...


2

You need to url-encode the data, and the easiest way to do this is to get curl to do it for by replacing the -d option by --data-urlencode. Also, you need to use double quotes or the shell will not expand the variable, so we have curl \ -H "Accept: application/json" \ -X POST \ --data-urlencode "${payload}" \ ...


1

The problem is here: '-15 minutes "$n"' Single quotes stop variable substitution, so you're literally passing "$n" in rather than the contents of the variable. Write: /opt/bin/date --date "-15 minutes $n" '+%Y-%m-%dT%H:%I:%S' instead.


1

Under set -e, the non-existence of failfailfail causes the whole script to exit (or the subshell, if the function is executed in a subshell). If you don't need to modify the shell state from the function, you can run it in a subshell. myfunc() ( set -e ls failfailfail uptime ) Another approach in bash is to set an ERR trap to execute ...


1

This is the closest you can get: your_main_command && run_on_success || run_on_failure The caveat is that run_on_failure will be run if any of the preceding commands i.e. you_main_command or run_on_success fails.


1

You ommited a dollar sign in command substitution here: ctfPadded=(printf ${ctflist}00000000) This line should read: ctfPadded=$(printf ${ctflist}00000000)


1

Shells don't perform tilde expansion inside quotes, so your "~/.cache" doesn't point to your home directory—it points to a subdirectory .cache of a directory called ~. Remove the quotes, and everything should work as expected: export XDG_CACHE_HOME=~/.cache


1

It's possible if you use two non-portable things: GNU awk's two-way I/O (see relevant StackOverflow answer); millisecond output with date (see this ServerFault answer). With that, you can prefix the input with timestamps like that: awk '{"date +%Y%m%d%H%M%S%3N" |& getline timestamp; print timestamp,$0; close("date +%Y%m%d%H%M%S%3N")}' ...


1

echo $(hostname) does not work, as you already realized, since the command is expanded. Use single quotes ' to prevent command expansion: echo '$(hostname)'


1

Normally, screen accepts a command and arguments, so this might work: screen -m -S 'test' nohup ~/<script-to-be-run>.sh Because it is not expecting a variable assignment, and the variable might otherwise be reset, you would probably have to add env to set the variable: screen -m -S 'test' env DISPLAY=:0 nohup ~/<script-to-be-run>.sh'


1

Using "awk" As @Theophrastus has noted above, neither bash nor bc support scientific notation. For simple comparisons and calculations, I suggest using awk (which does handle xEy numbers): a=10e-12 b=12e-12 r=$(awk 'BEGIN{print ('$a'>'$b')?1:0}') echo $r For more complex expressions, you can avoid the cumbersome quote handling and escaping by ...


1

Since the current path is not in the PATH variable, you have to specify completely the location of the file: you can add "./" if your file is in the same location as the script or you can give the full path: ./goodmain Or: /full/path/goodmain


1

The following should work with python 2 and 3, save as xyz.py and run with python xyz.py file_1 file_2 file_3: import sys import csv names = set() files = {} for file_name in sys.argv[1:]: b = files.setdefault(file_name, {}) with open(file_name) as fp: for line in fp: x = line.strip().split() names.add(x[1]) ...


1

As stated by steeldriver, if you use GNU sed, you can tell which occurrence should be replaced, e.g.: echo "/test/test/ 12 /test/test" | sed -n -e 's_/._/_2 p' If you can not make use of this feature you can also write: echo "/test/test/ 12 /test/test" | sed -n -r -e 's_(/[a-z]([a-z]+))\1_\1/\2_ p' Biliography: http://www.grymoire.com/Unix/Sed.html ...


1

You can try: dbsetup="CREATE DATABASE ${newsitename}_db;GRANT ALL PRIVILEGES ON ${newsitename}_db.* TO 'site_usr'@'localhost';FLUSH PRIVILEGES;" Double quotes will corrupt your string.


1

I say create a second script like this: #!/bin/bash echo -e "$(date)\n" # of course format date to your needs cat <&0 exit $? This will work like: (... all your commands & pipes...) | new_script >output.file Explained: First echo the date and a newline, then catenate STDIN and finally exit with the last (cat's) exit code.


1

"logger" You might also want to take a look at logger, a somewhat neglected command for writing messages to the system log (or journal) in the system's standard log output format. This won't help you if your application maintains its own logfile, but depending on the circumstances, there might be good design rationales to use the standard system logging ...


1

You can export your variables: VAR=foo export VAR or: export VAR=foo However, these variables will be visible in the environment of all subprocesses.



Only top voted, non community-wiki answers of a minimum length are eligible