New answers tagged

0

With GNU sed and date: sed -En 's#^Password=.*@([0-9]{2})([0-9]){2}$#date -d "\2/\1 +10 days" +%F#ep'


0

There are a few technical things wrong with your script/approach, but forgetting the technical details for a moment, at an intuitive level what you are trying to do is set some counting process in motion, then at some point in the future - you want to interactively query the process to see how things are going by trying to reference the variable value ...


7

Try: find . -name 'file.txt' -exec sed command {} + This finds all files named file.txt that in subdirectories of . and runs sed command against those files. If you want sed to modify those files in place, then add the -i option. Althought -exec ... + is now required by POSIX (hat tip: jordanm), some people may be using old versions of BSD find that do ...


2

You can do source /path/to/script or . /path/to/script To run the commands in the script in the current bash session. Note: do not call exit from the script in that case since it will finish your current session (likely before you can see the time if the terminal emulator closes on shell exit). On the other hand, if you are only measuring session ...


6

Aliases are only expanded if the command appears directly in the code, without any expansion. Writing things like \a, $V, $(echo a), etc. suppresses alias lookup. In addition, bash (unlike other shells) doesn't expand aliases in scripts by default anyway, so a actually does not run the alias in bash. Use a function instead of an alias. You'll need to use ...


1

It like you're saying: #!/bin/bash V=a alias $V="echo test" echo `a` #echo the out put of the 'echo test' command which is test echo `$V` #echo the output of $V 'command' which is holding a value itself and it won't be executed as an alias since it's not used directly. EDIT: Sorry I was wrong about saying that variables cannot be ...


2

First, local i=$1 assigns the value of $1 to i. $1 is the first argument of the function. Or outside of a function, it stands for the first positional parameter of a command or script. The following are quite intuitive. -i means the variable is an integer. local f declare -i i declare -i f Now to the long one. I'll break it down into separate ...


3

Assuming a shell like bash or ksh: max_time=3 SECONDS=0 IFS=$'\n:' grep -v '^#' ref.txt | while read tag cmd; do if (( SECONDS < max_time )); then echo "starting '$cmd' (tag is '$tag')" sleep 2 # for simulation purposes else echo "did not have time to start '$cmd' (tag is '$tag')" fi done This will give the ...


1

logic to display the processes which haven't started after 180 secs. Assuming the shell is a bourne shell. I testing on bash and zsh # ... # generate a timestamp in seconds since UNIX epoch START_TIME=$(date '+%s') until [[ $(date +%s) -gt $((START_TIME + 180)) ]] do # greps for the processes running echo " N number of processes are running" #&...


0

This can be put into CRON by editing crontab -e or manually started. #!/bin/bash mkdir -p ~/Downloads/themes-mint/ mv ~/Downloads/themes-mint/themes.zip ~/Downloads/themes-mint/themesOLD.zip mv ~/Downloads/themes-mint/icons.zip ~/Downloads/themes-mint/iconsOLD.zip wget -O ~/Downloads/themes-mint/themes.zip https://github.com/linuxmint/mint-y-theme/...


0

The following sh shell loop will remove all spaces, underscores and dashes from the names of files in the current directory, taking care to not overwrite any existing files: for f in *; do test -f "$f" || continue nf=$( echo "$f" | tr -d ' _-' ) ! test -e "$nf" && echo mv "$f" "$nf" done For bash and ksh, and being slightly more ...


0

|| logical OR {} begin-end of a function or set of commands for 3 arguments: initialization, condition, iterator change { f=$(( i - 1)); f=$(factorial $f); f=$(( f * i )); echo $f; } inline function giving back a number


0

You can use pacman -Qeq instead of pacman -Qe | awk '{print $1}'. And pacman can not install AUR packages, better keep them in a separate list or use an AUR helper like pacaur or yaourt. So, if you use an AUR helper like pacaur, you can export all explicitly installed packages with: pacman -Qqe > package_list.txt Or if you prefer only native and ...


7

Grep interprets \n as a newline character. It looks like your file does not have newline characters, it has \ followed by n. To search for literal backslashes, you must double them: $ grep -o '\\n[^\\]*\\n' o.txt \n29\n \n3 days\n \n59\n \n7 days\n \n99\n \n12 days\n With GNU grep, the output can be easily cleaned up to remove the \n: $ grep -oP '(?<...


15

There's often confusion between process forking and execution. When you do at the prompt of a bash shell. $ sh -c 'exec env ps' The process P1 issuing that $ prompt is currently running bash code. That bash code forks a new process P2 that executes /bin/sh which then executes /usr/bin/env, which then executes /bin/ps. So P2 has in turn executed code of ...


5

Yes, a program can know who its parent is. To illustrate, let's create two bash scripts. The first one reports its PID and starts the second script: $ cat s1.sh #!/bin/bash echo s1=$$ bash s2.sh The second script reports its process ID, the PID of its parent, and the command line used to run the parent: $ cat s2.sh #!/bin/bash echo s2=$$ PPID=$PPID ...


0

IMO, using printf to pipe commands into ed is better than sed -i. printf '%s\n' 'g/,888,/d' 'w' | ed -s msalik.txt The first arg to printf tells it to print each remaining argument separated by newlines (\n). Neither of the last two arguments really need quoting. I just quoted them as an example - some ed commands will need to be quoted. Why is ed ...


0

Well, I corrected the typo, which was certainly breaking the programme, and I fixed the syntax of the operator, also definitely breaking it. However (and this may seem ridiculous), once I corrected those issues, I preformed the valid=${#validCheck} operation manually to test the length of the string just in case and found that the directory's length was ...


1

To answer the question posed in the title succinctly: if [[ "$foo" -lt "$bar" ]]; then echo "$foo is less than $bar" fi The tests for integer comparisons are: n1 -eq n2 True if the integers n1 and n2 are algebraically equal. n1 -ne n2 True if the integers n1 and n2 are not algebraically equal. n1 -gt n2 True if the integer n1 is ...


0

Use ls -c to sort by ctime, and uniq to see if they're the same. ls -crntq | tail -4 | awk '{print $5}' | uniq -c | grep -q "^\s*4\s" && exit


2

GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu) This works well. Here is the full script: #!/usr/bin/env bash clear number1=8 number2=2 printf 'The sum of %d and %d = %d\n' $number1 $number2 $(( number1 ** number2)) And you just use the chmod +x filename; ./filename If you use another shell, you may need to point the interpreter, and run ...


1

zsh -c 'zmodload zsh/stat [[ $(zstat -N +size -- *(.om[1,4])) =~ $'\''(.*)\n\\1\n\\1\n\\1'\'' ]]' && exit Would exit if the 4 newest non-hidden regular files in the current directory all have the same size. On a GNU system, you could also do: find . -maxdepth 1 ! -name '.*' -type f -printf '%T@ %s\n' | sort -rn | awk 'NR == 1 {v = $0}; v != ...


3

You appear to be running the script in the dash shell. The error message that you quote is what dash outputs when it's failing to understand the ** operator (dash doesn't have it). It's the same error you get if you try to multiply something with nothing: $ echo $(( 2 * )) dash: 14: arithmetic expression: expecting primary: " 2 * " Make sure that you ...


0

There are several places where you could have used a script besides ~/.bashrc or /etc/profile; without providing details on what changes you made, you will get only general advice. For instance, you might have modified or added a file in /etc/profile.d modified your ~/.profile or ~/.bash_profile run the terminal via a script (or desktop "launcher") You ...


0

Using grep grep -vw '888' infile.csv > outfile.csv If you want to edit inplace, sed -i.bak '/\b888\b/d' infile.csv Edit: To delete lines containing 888 only in 4th column sed -i.bak -r '/^(([^,]+,){3})888,/d' infile.csv


3

Using sed, sed '/888/d' filename You can use, -i option to edit file in-place like, sed -i.bak '/888/d' filename Note : .bak will keep backup of original file. Assuming, you want to get rid of lines which contains 888 on specific column, then you would want to use, awk -F"," '$4 != "888"' filename


0

A simple echo will remove space fromboth front and back db_cnt=$(echo $db_cnt) If you want to remove the whitespace just in front but want to preserve spaces at the end of variable, you can do it using sed as db_cnt=$(echo "$db_cnt" | sed 's/^ *//')


1

switch..case is most suitable when there is more than one choice for readability and maintainability (adding options). In terms of performance, both are pretty much the same.


2

Your script is working here. The only way to make it produce the same error you report is to make the variable db_ctdy_sr contain a new line: Add a new line: source db_count.ini db_ctdy_sr=$' 7\r' And then test the script: $ ./so Value of db:7 ")syntax error: invalid arithmetic operator (error token is " The value of db: //test if working //test if ...


0

I will add this : Dont make the script to be called directly, but to call a secondary script, the first script will be used to do log: #!/bin/bash [ "$USER" != "www-data" ] && exit set -a sudo realscript &>/var/log/myscript.log and the realscript: [ "$USER" != "root" ] && exit In sudo, put the realscript as sudo permitted ...


3

To trim whitespace from the front of db_cnt variable in bash use: db_cnt="${db_cnt#"${db_cnt%%[![:space:]]*}"}" Example: $ db_cnt=" 7" $ echo "$db_cnt" 7 $ db_cnt="${db_cnt#"${db_cnt%%[![:space:]]*}"}" $ echo "$db_cnt" 7 $ You can use the syntax to customise your script in whatever way you want.


0

To read data from the file that an executable is stored in: #!/bin/bash old_dir="$(pwd)" cd "$(dirname "$0")" this_dir="$(pwd)" cd "${old_dir}" unset old_dir # read from where executable is stored echo "${this_dir}/data" # read for present working directory echo "$(pwd)"


1

You have to add /var/lib/app/ directory to your PATH, not /var/lib/app/startapp.sh. To do this permanently, first take a look at your PATH environment variable by entering this command: echo $PATH The output you will get, will be something like: /usr/local/bin:/bin:/usr/bin/:usr/local/sbin:/usr/sbin/ ... You shouldn't alter the order, so while exporting ...


0

Setting aside whether your approach is a good idea or not, if mycommand is interactive you should inhibit shell escapes using the noexec directive. This prevents the execution of other commands by presetting the exec() system calls to do nothing. (This is achieved through the mechanisms around LD_PRELOAD, see sudo.conf(5).) Caveat: this is not bulletproof - ...


2

One of the best thing is to use the "Digest_Spec" possibility in the sudoers file, to validate the checksum of your executable Extract of the man page: If a command name is prefixed with a Digest_Spec, the command will only match successfully if it can be verified using the specified SHA-2 digest. Using openssl, to generate the checksum: $ openssl ...


0

Bash executes the code in the variable PROMPT_COMMAND before printing the prompt. One of the things you can do that is to calculate components of the prompt which are then assembled via the PS1 setting. PROMPT_COMMAND_set_status () { if ((last_status == 0)); then PS1_status= else PS1_status="[$last_status] " fi } PS1=PS1='${debian_chroot:+($...


0

Try using echo -e "1\n2" piped to the script. Just put the menu responses separated by newlines (\n) in the string after -e. echo -e "1\n2" | operation.sh Another option is to put the responses in order one per line in a text file. You can then cat that file and pipe it to the script. cat responses.txt | operation.sh


0

Answer intended for original version of question For your one command, replacing the grep-tail-grep-if commands, try: awk '/status change/{last=$0} END{printf "It is %sBackup\n",(last~/Active/?"":"not ")}' "/apps/tests/$2" How it works: /status change/{last=$0} Every time that a line containing status change is found, it is saved in the variable last. ...


2

Using sed Here is one way: $ sensors -Af | sed -n '2{s/°.*//; s/[^+-]*//; p; q}' +105.8 Or, using the same command inside command substitution to capture its output in a variable: temp=$(sensors -Af | sed -n '2{s/°.*//; s/[^+-]*//; p; q}') s/°.*// removes the first occurrence of the degree symbol, °, and everything after it. s/[^+-]*// removes ...


0

If only the numbers 0 through 9 are allowable as input, all you need is a simple IF statement. #!/bin/bash echo -n Please enter a single digit: read single_digit if [ $single_digit -lt 10 ]; then echo Thanks for $single_digit else echo Screwball!!! I said SINGLE DIGIT!! fi


0

For a 2 column output format with "dirName numFiles", where "dirName" is one of "/ /bin /usr /usr/sbin" "numFiles is the count of files in above directory being >100K You could also use : $ for i in / /bin /usr /usr/bin; do echo -en "$i " ; find $i -maxdepth 1 -size +100k | wc -l; done | column -t Example output: / 0 /bin 46 /usr ...


6

You need a space between the [ and the ! for things to work correctly. This is because [ is implemented as shell-builtin command (it even used to be a separate exectuable /usr/bin/[). You can also use: if [ ! -d "/home/unix/POSTagger2" -o ! -d "/home/unix/POSTagger2/stanford-parser-full-2015-12-09" -o ! -d "/home/unix/POSTagger2/stanford-corenlp-full-2015-...


12

You are missing some spaces, for example [! must be [ ! and "] must be " ] look to the corrected code: #!/bin/bash if [ ! -d "/home/unix/POSTagger2" ] || [ ! -d "/home/unix/POSTagger2/stanford-parser-full-2015-12-09" ] || [ ! -d "/home/unix/POSTagger2/stanford-corenlp-full-2015-12-09" ] then echo "Nope" fi Another way for your code: #!/bin/...


0

If you don't have thousands of ".sh"-files, and no sub-directories ending in ".sh", you could use: gawk -i inplace 'NR==1 && $0=="#!/bin/sh" {$0="#!/bin/bash"} 1' *.sh


4

find . -depth -iname proj -type d -execdir mv {} test \; You need a find implementation with support for the non-standard -execdir predicate, but find implementations that support -iname generally also support -execdir in my experience.


4

You can create conditions and expressions inside $() like this: echo "$( var=2; echo $var)" in your example you can change PS1 variable like this: PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w $( status=$?; (( status != 0 )) && echo "[$status] " )\$ ' looks like: jackman@b7q9bw1:~ $ echo hello hello jackman@b7q9bw1:~ $ sh -c 'exit 42' ...


0

I am a fan of look arounds to do this kind of work. I copied you example data into a text file named "test" and then ran the following $ grep -oP '(?<=s\_).*(?=\_v)' test 8493020020 7483920322 grep -o means return only the match -P means use Perl regex ?<= means "match anything that comes after s_" ?= means "match anything that comes before v_" ...


3

Things that can affect the setuid program Let's consider some ways the calling user could affect the behavior of the setuid process. I'll divide the things to consider in three groups: 1) the program itself, 2) the input to the program, and 3) the environment it runs in. The binary: If the unprivileged user can modify the binary that will be run, that ...


2

You can't directly set values to the positional paramaters like this. You can set them with the set command, but this will set all the values ($1, $2, ...) e.g. $ set -- first second third fourth fifth $ echo $1 first $ echo $2 second Now there are two cases where $2 can be the empty string; first if no value has been passed, or second if "" is passed ...


0

You can utlizise this perl script for your perpose: #!/bin/perl my $str = "moveover_virus_7483920322_virus.csvwork"; my $phone = (split /_/, $str)[2]; print "$phone\n"; test the script: [iahmad@ijaz-cms ~]$ ./perltest 7483920322



Top 50 recent answers are included