w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
In bash script parameter tracking
You need to use getopts inside your script. Something like this should work: while getopts "c:s:" optionName; do case "$optionName" in s) arg="$OPTARG"; echo "-s is present with [$arg]";; c) arg="$OPTARG"; echo "-c is present with [$arg]";; esac done

Categories : Bash

pass parameter from bash to mysql script
MySQL doesn't support session variables in a LOAD DATA INFILE statement like that. This has been recognized as a feature request for quite some time (http://bugs.mysql.com/bug.php?id=39115), but the feature has never been implemented. I would recommend using mysqlimport instead of doing the complex steps with mysql that you're doing. The file's name must match the table's name, but you can trick this with a symbolic link: #!/bin/bash for file in *.symbol do path="/home/qz/$file" ln -s -f "$path" /tmp/lasp.txt mysqlimport -u qz -h compute-0-10 -pabc --local --columns "score,symbols" /tmp/lasp.txt done rm -f /tmp/lasp.txt PS: No need use `ls`. As you can see above, filename expansion works fine.

Categories : Mysql

Bash script being passed one parameter, but I want multiple
Try: eval set "$@" or (safer if it might begin with shell options): eval set -- "$@" After that you should be able to use "$@". As with all evals, this has all kinds of dangers. :-) Example of a danger: $ set '`ls`' $ eval set -- "$@" $ echo $# 28 $ echo "$1" COPYRIGHT Edit: here's a protect shell function and an example of using it. I am not sure I protected against everything, but it gets the two obvious cases: #! /usr/bin/env bash protect() { local quoted quoted="${1//$/\$}" quoted="${quoted//`/\`}" # use printf instead of echo in case $1 is (eg) -n printf %s "$quoted" } foo=expanded set -- '-e -n $foo `ls` "bar baz"' eval set -- "$@" echo "without protect, $# is $#:" for arg do echo "[$arg]"; done set -- '-e -n $foo `ls` "bar baz"' eval set -- $(

Categories : Bash

measuring runtime of bash script with & parameter in the body
Use the wait command to wait for the processes to finish, before measuring the time #! /bin/bash start1=`date +%s` ./a & ./a & ./a & ./a & ./a & wait # <---------------- end=`date +%s` runtime=$((end-start1)) echo "$runtime" You can also use the time command for better and more accurate results: time { ./a & ./a & ./a & ./a & ./a & wait # <---------------- }

Categories : Linux

How can I pass a variable onto a command's parameter in a bash script?
you need to use array: #!/usr/bin/env bash BACKUP_EXCLUDES=() function exclude { while (( $# )) do BACKUP_EXCLUDES+=(--exclude="$1") shift done } exclude /proc /dev /mnt /media exclude "/lost+found" rsync -ruvz "${BACKUP_EXCLUDES[@]}" / /some/backup/path the bash explanation: please check @janos answer the zsh explanation (if it was Zsh): when you used a string variable it was like you passed --exclude=""/proc" --exclude="/media" ..." - so it was treated as long path with spaces - which never matched.

Categories : Linux

Get string by regex bash script
As the delimiter before 20 and 80 is :, you can mainly do it with cut: $ cut -d: -f2 file 22 80 With bash: $ while read line do echo ${line#*:} done < file 22 80 Even with awk: $ awk -F: '{print $2}' file 22 80 And to complete it, with sed: $ sed 's/.*://' file 22 80

Categories : Bash

Editting a string variable in a bash script
Use sed to do an in-place edit. (-i option). This can be called from bash. sed -i -e 's/c_defaultss[-s]+//g' filename Use Perl to do an in-place edit. (-i option). Invoked by bash. > perl -pi -e 's/c_defaultss[-s]+//g' filename

Categories : Regex

Bash Script to process data containing input string
Kevin, you could try the following: #!/bin/bash directory='/home' tag=$1 for files in $directory/*$tag* do if [ -f $files ] then #do your stuff echo $files fi done where directory is your directory name (you could pass it as a command-line argument too) and tag is the search term you are looking for in a filename.

Categories : Linux

running one command, n time at the same time with different parameter like parallel for using bash script
May be you can use std::thread... #include <iostream> #include <thread> #include <string> void runcmd(std::string param) { // something like system(param.c_str()); } int main() { std::thread* threadarray[10]; for (int i=0; i<10; ++i) threadarray[i] = new std::thread(runcmd,"./a"); for (int i=0; i<10; ++i) { threadarray[i]->join; delete threadarray[i]; } return 0; } I think you can specify core id with sched_setaffinity. look: http://www.thinkingparallel.com/2006/08/18/more-information-on-pthread_setaffinity_np-and-sched_setaffinity/

Categories : C++

RegExp for a bash script that removes html garbage from a string
Removing html tags (and script, and style) is not always easy with regex, but since you are looking for a bash way, you can use a simple trick: using a text browser (lynx, links, w3m), example: lynx -dump input.html > output.txt Or you can use the inline tool xidel with an XPath query: xidel ./input.html --extract "//text()[not(parent::style|parent::script)]" You can try with regex too, but it is less safer: sed 's/<script.*</script>|<style.*</style>|<[^>]*>//g' input.html (note that this regex fails with something like: <script>sfsdfsfsdf</script> CONTENT <script>sdfsdfsdf</script>) or you can use this regex that is a little more safer in an html context: sed -r 's/<script([^<]|<[^/]|</[^s]|</s[^c])*</scrip

Categories : HTML

Linux Bash Shell Script: How to "ls" a directory and check some output string?
To check for a directory: if [ ! -d '/var/aaaaaaa' ]; then echo 'no dir!' fi For file: if [ ! -f '/var/aaaaaaa' ]; then echo 'no file!' fi To check output: if ls '/var/aaaaaaa' 2>&1 | grep 'No such'; then echo 'no such'; fi To check when ls fails: if ! ls '/var/aaaaaaa' &> /dev/null; then echo 'failed' fi

Categories : Linux

Bash script to wait for gnome-terminal to finish before continuing script, only works for first instance of script
#!/bin/bash date bash -c "sleep 7" & bash -c "sleep 5" & wait date As you can see while running this script, both sleep commands will run in parallel, but main thread stalls, while they are running. Sat. Jule 27 01:11:49 2013 Sat. Jule 27 01:11:56 2013 Replace sleep 7 with expect launchneuron.exp and sleep 5 with expect launchmpj.exp and add your plot commands after calling "wait": echo "Simulation Complete" ...(your code to plot results)

Categories : Bash

Why does the child of an eval call from bash get orphaned once the parent bash script dies?
This is normal and expected. You sent a signal (presumably SIGTERM) to parent-script and it died, but no signal was sent to another-script. It keeps on running. This is different than what happens when the parent-script job is running interactively on a terminal and you type ^C (or ^Z). In that case, a SIGINT signal is automatically sent to the whole foreground process group. Since another-script is un the same process group as parent-script (by default), they both get the signal and they both die. If you want another-script to die automatically when its parent dies in any other context than when it's a job running in a terminal with job control, you have a few options. parent-script can trap the SIGTERM signal. In the signal handler, it kills its child, and then exits itself. This, o

Categories : Linux

Pass a full bash script line to another bash function to execute
optout is a command like any other, and so must be preceded by any local modifications to the environment. The command that optout runs will inherit that environment. CC=${BUILD_TOOL_CC} optout ./configure ${ZLIB_CONFIGURE_OPT} --prefix=${CURR_DIR}/${INSTALL_DIR} By the way, this is just one of the problems you are likely to encounter with your optout function. You cannot run arbitrary command lines in that fashion, only a simple command followed by zero or more arguments (and I would expect there are some exceptions to even that restricted set, as well).

Categories : Linux

BASH: how to define an array as environment variable before calling a bash script
Incredibility weird.... I have never seen that before. It looks like the array is not passed to the subshell. One way around this is to source the script instead of executing it: declare -a MYARR=( 1 2 ); . ./myscript.sh

Categories : Arrays

'Globalize' Bash functions inside of a bash script
You can use this command in your startup.bash: source lib.bash the source command runs the file in the current shell environment, unlike using bash lib.bash (or . lib.bash) which creates a new, separate environment for that script (and only that script) and is why the function is not carried over. (source)

Categories : Linux

escaping bash 'test' keywork in a bash script
test is a Bash builtin command, not a keyword or reserved word. This means Bash will only interpret it if it is the first token in a command, like test blah In python manage.py test Bash will just pass it as a parameter to python (that is, it will execute python with two parameters, manage.py and test); you don't need to escape it. In general, Bash doesn't have reserved words in the sense of C-like languages. The only things you need to escape are whitespace (which Bash uses to separate params), and certain symbols including $(&|; which Bash uses for its variables and command separators.

Categories : Bash

Can One Bash Script Launch Multiple Other Bash Scripts?
Run them in the background, just like you would in an interactive shell. command1 & command2 & command3 & wait # Wait for all background commands to finish The commands can be just about anything, not just other bash scripts.

Categories : Linux

how to create a script from a perl script which will use bash features to copy a directory structure
First, I see that you want to make a copy-script - because if you only need to copy files, you can use: system("cp -r /sourcepath /targetpath"); Second, if you need to copy subfolders, you can use -r switch, can't you?

Categories : Perl

bash shell script error works on command line, not in script
Variables are supposed to contain data, and bash treats them as data. This means that shell meta-characters like quotes are also treated as data. See this article for a complete discussion on the topic. The short answer is to use arrays instead: ASCIIDOC_OPTS=( --asciidoc-opts='-a lang=en -v -b docbook -d book' ) DBLATEX_OPTS=( --dblatex-opts='-V -T db2latex' ) cmd=(a2x -v -f pdf -L "${ASCIIDOC_OPTS[@]}" "${DBLATEX_OPTS[@]}" "$1".asciidoc) # Print command in pastable format: printf '%q ' "${cmd[@]}" printf ' ' # Execute it "${cmd[@]}" Make sure not to use eval: eval "$cmd" #noooo This will appear to work with your code as you posted it, but has caveats and security problems.

Categories : Bash

dump files from bash script in different directory from where python script ran it
You should change directory within the same command: cmd = "/path/to/executable/executable" outputdir = "/path/to/output/" subprocess.call("cd {} && {}".format(outputdir, cmd), shell=True)

Categories : Python

How to pass output from remote script to local script in bash
On your local script, in your ssh line, you can redirect some of the outputs to a file with tee: ssh ... | tee -a output.log If you want to filter which one goes to the output.log file, you can use process substitution: ssh .... | tee >(grep "Some things you want to filter." >> output.log) Besides grep you can use other commands as well like awk.

Categories : Bash

Create bash script with menu of choices that come from the output of another script
This might work for you: #!/bin/bash # Set the prompt for the select command PS3="Type a number or 'q' to quit: " # Create a list of customer names and numbers (fill gaps with underscores) keys=$(/usr/local/bin/info $1 | sed 's/ /_/g') # Show a menu and ask for input. select key in $keys; do if [ -n "$key" ]; then /usr/local/bin/extrainfo $(sed 's/.*_11111/11111/' <<<"$key") fi break done

Categories : Bash

BASH: How To Create a Setup Script to build another script
This answer, a work in progress; Your code while [ "$index" -lt "$elements" ] do ????????? echo "Your Directory is ~/$root/${gitdir[0]}/${gitdir[1]}/${colours[2]}" done becomes fullPath="/${root}/" index=1 while [ "$index" -lt "$elements" ] ; do # append values from $gitdir until you are done fullPath="${fullPath}/${gitdir[$index]}" (( index++ )) done # not sure how colours got introduced to this but same idea fullPath="${fullPath}/${colours[2]}" echo "Your Directory is ~/${fullPath}" use of (( index++ )) implies using a version of bash, ksh, zsh (maybe others) that support arithmetic evaluations. That said, it's not clear what your input into gitdir[@] will be and why you need to "count" the levels. Why not just accept user input as arguments, document the o

Categories : Arrays

Bash: increment a variable from a script every time when I run that script
A script is run in a subshell, which means its variables are forgotten once the script ends and are not propagated to the parent shell which called it. To run a command list in the current shell, you could either source the script, or write a function. In such a script, plain (( n++ )) would work - but only when called from the same shell. If the script should work from different shells, or even after switching the machine off and on again, saving the value in a file is the simplest and best option. It might be easier, though, to store the variable value in a different file, not the script itself: [[ -f saved_value ]] || echo 0 > saved_value n=$(< saved_value) echo $(( n + 1 )) > saved_value Changing the script when it runs might have strange consequences, especially when yo

Categories : Bash

Run PBS script and post-process output within bash script
I don't believe PBSPro supports this, but TORQUE (another PBS derivative) has a -x option that you might be interested in. You can submit a job like this: qsub -I -x <executable> This would run your job interactively and run the executable, with all of the output directed to your terminal, and the job will execute as soon as that executable terminates. You could then begin post-processing at that point. PBSPro may have similar functionality, but what I've described here is for TORQUE.

Categories : Bash

how can i pass a variable from my php script and send it to my bash script
Try using shell_exec in your php script to execute your shell script and pass your variable, like so: $cmd="perl -pi -e 's/ : /:/g' /opt/lampp/htdocs/" . escapeshellarg($variable); $r=shell_exec($cmd); escapeshellarg is used to escape any potentially dangerous characters in $variable, to prevent a command line injection attack.

Categories : PHP

need to call a php script from bash script through eval
There are still some parts of your script that I don't understand, or not sure it does really work, but about your question, I think your callback could only work if you place it on a function like: function mycallback { php /srv/www/scripts/mage/install-invoke-app.php } And call your install_repolist function as install_repolist $gitRepos 0 mycallback That should make your php command call with the file argument work but there is one thing: I don't think values of gitRepos could actually be passed like that. Most parts of your code has variables that actually needed to be quoted around double quotes "". One problem with it is that your php command would just end up in the final place where it is executed as one single argument php and no longer with the file due to word splitti

Categories : PHP

How to source a csh script from inside a bash script
WARNING : don't put the following script in your .bashrc, it will reload bash and so reload .bashrc again and again (stopable with C-c anyway) Use preferable this script in your kit/CDS stuff startup script. (cadence presumably) WARNING 2 : if anything in your file2source fails, the whole 'trick' stops. Call this script : cshWrapper.csh #! /bin/csh # to launch using # exec cshWrapper.csh file2source.sh source $1 exec $SHELL -i and launch it using exec ./cshWrapper.csh file2source.sh it will : launch csh, source your file and came back to the same parrent bash shell Example : $> ps PID TTY TIME CMD 7065 pts/0 00:00:02 bash $>exec ./cshWrapper.csh toggle.csh file sourced 1 $> echo $$ 7065 where in my case i use the file toggle.csh #! /bin/csh # source

Categories : Misc

error C2664 cannot convert parameter 1 from 'std::string (__thiscall ClassName::* )(std::string)' to 'std::string (__cdecl *)(std::string)
In your real use-case can you simply make FunctionToBePointed a static method? static std::string Class1::FunctionToBePointed(std::string msg) { return msg; } If yes your code should work. The reason is that instance methods are implicitly called with an hidden this pointer, this is the thiscall calling convention, whereas static methods simply use the cdecl convention because they don't work on any instance. EDIT: A sample with Boost::bind: The MyClass C# class: using System; using System.ComponentModel; public class MyClass : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged = delegate{}; private string name; public string Name { get { return name; } set { if (name

Categories : Visual C++

Passing in a Parameter in Google Spreadsheet Script from Script Assignment
You could do a couple of things - Ask the user for the input using Browser.inputBox Read cell's value from the script itself (if the cell reference is always constant) using an example like SpreadsheetApp.getActiveSheet().getRange("A1")

Categories : Google Apps Script

Executing bash script from php script
I would have a directory somewhere called scripts under the WWW folder so that it's not reachable from the web but is reachable by PHP. e.g. /var/www/scripts/testscript Make sure the user/group for your testscript is the same as your webfiles. For instance if your client.php is owned by apache:apache, change the bash script to the same user/group using chown. You can find out what your client.php and web files are owned by doing ls -al. Then run <?php $message=shell_exec("/var/www/scripts/testscript 2>&1"); print_r($message); ?> EDIT: If you really want to run a file as root from a webserver you can try this binary wrapper below. Check out this solution for the same thing you want to do. Execute root commands via PHP

Categories : PHP

Update string at a specific line so it doesn't update duplicates in string?
The quickest solution would be to keep the array returned by Split and then use String.Join to rebuild what you started with.

Categories : C#

Posting a string parameter using ajax not working when the parameter value contains html tags
My first guess would be you're not allowed to post HTML encoded content to the action; therefor also the question: Which Server Error do you get when posting? You can turn off the ValidateRequest (for the page or the site), but I doubt you'd want that for that entire site; you could also try to replace the < and > in the description to &lt; and &gt; before posting and undo that replace in the SaveDescription tag (not really a desired solution). Also take a look at these answers: Allow user to input HTML in asp.net MVC

Categories : HTML

Bash parameter substitution in xinitrc
Try: desktop=fluxbox startx Environment variables are set by putting them before the command name; everything after the command name is just arguments to the command.

Categories : Bash

Bash: Why does parent script not terminate on SIGINT when child script traps SIGINT?
New answer: This question is far more interesting than I originally suspected. The answer is essentially given here: What happens to a SIGINT (^C) when sent to a perl script containing children? Here's the relevant tidbit. I realize you're not using Perl, but I assume Bash is using C's convention. Perl’s builtin system function works just like the C system(3) function from the standard C library as far as signals are concerned. If you are using Perl’s version of system() or pipe open or backticks, then the parent — the one calling system rather than the one called by it — will IGNORE any SIGINT and SIGQUIT while the children are running. This explanation is the best I've seen about the various choices that can be made. It also says that Bash does the WCE appr

Categories : Linux

Code First Migrations - Update-database -script command generated SQL script not working
The -Verbose output just shows a summary of statements. If you run your command manually in SQL Server Management Studio then you need a GO between the two statements: ALTER TABLE [dbo].[Posts] ADD [Abstract] [nvarchar](max) GO UPDATE dbo.Posts SET Abstract = LEFT(Content, 100) WHERE Abstract IS NULL The quick fix is to do something like: update-database -script then use Sql Server management Studio to do the following search and replace in the generated script: find what: ^{:b*}{{INSERT|UPDATE|SELECT|DELETE}.+} (this finds any CRUD statements) replace with: 1GO 12 (keep the indents, and add GO before any CRUD statements) Find options: Use regular expressions But, note that -Verbose doesn't give you the output you want, you need the output from -Script, or you will be missing the

Categories : Entity Framework

bash and grep: passing of regex parameter
Change regex="^'$1$'" to regex="^$1$" and $($cmd) to $cmd Here is a fixed version: #!/bin/bash DICT=/usr/share/dict/ngerman usage () { progname=$(basename "$0") echo "usage: $progname regex" } if [ $# -le 0 ]; then usage exit 1 fi regex="^$1$" cmd="grep -i $regex $DICT" echo "$regex" echo "$cmd" $cmd | while read -r word; do echo "$word" done But this script has potential problems. For example try running it as ./script 'asdads * '. This will expand to all files in a directory and all of them are going to be passed to grep. Here is a bit improved version of your code with correct quoting and also with bonus input validation: #!/bin/bash DICT=/usr/share/dict/ngerman usage () { progname=$(basename "$0") echo "usage: $progname regex" } if [ $# -le 0 ]

Categories : Regex

How to get a bash parameter substitution to work properly?
Use lowercase variable names. $PATH and $USER are special. To parse the string, you can use a regular expression: [[ $var =~ (.*)@(.*):(.*) ]] user=${BASH_REMATCH[1]} host=${BASH_REMATCH[2]} path=${BASH_REMATCH[3]} Update: For a possibly missing user, you can change it to [[ @$var =~ (.*)@(.*):(.*) ]] user=${BASH_REMATCH[1]#@}

Categories : Regex

What does the k parameter do in the sort function (Linux Bash Scripting)?
KEYDEF is F[.C][OPTS][,F[.C][OPTS]] for start and stop position, where F is a field number and C a character position in the field; both are origin 1, and the stop position defaults to the line's end. If neither -t nor -b is in effect, characters in a field are counted from the beginning of the preceding whitespace. OPTS is one or more single-letter ordering options [bdfgiMhnRrV], which override global ordering options for that key. If no key is given, use the entire line as the key. An example input file: 123 233 214 176 341 325 sort on the first field: sort -t' ' -k1 input Gives: 123 233 214 176 341 325 The second field: sort -t' ' -k2 input Gives: 214 176 123 233 341 325 Second and third digits of the first field: sort -t' ' -k1.2

Categories : Linux



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.