source_id
int64
1
74.7M
question
stringlengths
0
40.2k
response
stringlengths
0
111k
metadata
dict
293,800
I am trying to send ipv6 pings from a computer in a LAN. Unfortunately it does not work. It seems that I have an ipv6 address in the LAN, but somehow the ping -Ieth1 ipv6.google.com just prints a connect: Network is unreachable . Here is my routing table: Kernel IPv6 routing table Destination Next Hop Flag Met Ref Use If fe80::/64 :: U 256 0 0 eth1 ::/0 :: !n -1 1429877 lo ::1/128 :: Un 0 5 6 lo fe80::9a90:96ff:fea4:e451/128 :: Un 0 2 5 lo ff00::/8 :: U 256 8 99924 eth1 ::/0 :: !n -1 1429877 lo And this is the output of ifconfig : eth0 Link encap:Ethernet HWaddr 98:90:96:a4:e5:49 UP BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) Memory:fb300000-fb37ffffeth1 Link encap:Ethernet HWaddr 98:90:96:a4:e4:51 inet addr:172.20.33.53 Bcast:172.20.35.255 Mask:255.255.252.0 inet6 addr: fe80::9a90:96ff:fea4:e451/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:946567 errors:0 dropped:0 overruns:0 frame:0 TX packets:322832 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:144448246 (144.4 MB) TX bytes:68655794 (68.6 MB) Interrupt:20 Memory:fb400000-fb420000lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:65536 Metric:1 RX packets:463549 errors:0 dropped:0 overruns:0 frame:0 TX packets:463549 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1 RX bytes:113166471 (113.1 MB) TX bytes:113166471 (113.1 MB) Any ideas on what might be the cause and what can I change?
You have only Link-Local, non routable ipv6 (fe80::/10). So You have no public routable IPv6. In this configuration You can make ipv6 connect only to Link-Local addresses in same L2 segment.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/293800", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/57266/" ] }
293,851
I have this file: 1 2 2 7 3 4 4 7 5 3 6 7 7 1 8 2 9 4 And my desired output is 1 13 2 17 3 7 In my input i have 9 rows and i want to reduce it to three rows while preserving the total amount of 2nd column. For example 1 in 1st column represnts 1,2,3 and 13 in 2nd column, 1st row represent addition (2+4+7) and so on.. Any idea? may be by using awk/ perl or any other linux tool.
Here is an awk solution: awk '{ s+=$2; if (!(NR%3)) { k++; print k,s; s=0 } }; END { if (NR%3) { k++; print k, s } }' file.txt It ignores the first column, preferring to generate it in k as an output row number. The second column is summed in s , and every three lines ( (NR % 3) == 0 ) it's output and the accumulator reset. Finally, if we have any left-over lines we output the remaining sum. Output from the example file 1 132 173 7 Just for completeness, here is a DRY version that uses a function to handle the repeated code from the modulo-3 and END blocks: awk 'function outsum() { print ++k,s; s=0 }; { s+=$2; if (!(NR%3)) { outsum() } }; END { if (NR%3) { outsum() } }' file.txt
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/293851", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/177673/" ] }
293,871
I'm trying to change my directory to /boot/efi, but running sudo cd /boot/efi does nothing. I'm on fedora 23. Is there a more powerful command for this?
cd is a shell builtin, and sudo only works with programs. Try using either su - or sudo -i before changing directory. These will elevate your login session to that of the root user. Once finished making changes, make sure to type exit to return to being a normal user.
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/293871", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/175188/" ] }
293,876
Context I have been running archlinux on my laptop for years and never needed the microphone. Now I need it but cannot find a way to configure it properly. I use alsa and pulseadio . Running alsamixer as a user I have two gauges: || ||Master Capture I have both of them unmuted and enabled to sensible (~50%) values. Running alsamixer as root I have several gauges: || || || || || ||Master Headphones Speaker PCM Microphone MIC Boot || || || || ||Beep Loopback Internal Internal Capture If I enable the Loopback as root I can hear the microphone back through the speakers . If I explicitly select my sound card in alsamixer as a user I get the same commands as running as root (and if I enable Loopback here I do hear the microphone from the speakers as well). I get the following: (To the right are two more Internal gauges, the Loopback (enable/disable) and a mutable Off-hook ) Yet, no matter what I do and how much I meddle with the alsa gauges I never manage to pass the microphone to the user application. In essence, every time I run arecord I get the following output: $ arecord -vv -f dat /dev/null Recording WAVE '/dev/null' : Signed 16 bit Little Endian, Rate 48000 Hz, StereoALSA <-> PulseAudio PCM I/O PluginIts setup is: stream : CAPTURE access : RW_INTERLEAVED format : S16_LE subformat : STD channels : 2 rate : 48000 exact rate : 48000 (48000/1) msbits : 16 buffer_size : 24000 period_size : 6000 period_time : 125000 tstamp_mode : NONE tstamp_type : GETTIMEOFDAY period_step : 1 avail_min : 6000 period_event : 0 start_threshold : 1 stop_threshold : 24000 silence_threshold: 0 silence_size : 0 boundary : 6755399441055744000#+ | 00% aplay , on the other hand, works perfectly. My sound card is ( lspci ): # lspci| grep -i audio00:14.2 Audio device: Advanced Micro Devices, Inc. [AMD/ATI] SBx00 Azalia (Intel HDA) I looked at the arch wiki and tried setting the following in /etc/modprobe.d/modprobe.conf (and rebooted the machine): options snd-hda-intel model=dell-m6-dmic (I cannot get the microphone to send data to the user application with or without that configuration.) My current hda modules are: # lsmod |grep hdasnd_hda_codec_si3054 16384 1snd_hda_codec_realtek 69632 1snd_hda_codec_generic 69632 1 snd_hda_codec_realteksnd_hda_intel 32768 5snd_hda_codec 106496 4 snd_hda_codec_realtek,snd_hda_codec_si3054,snd_hda_codec_generic,snd_hda_intelsnd_hda_core 61440 5 snd_hda_codec_realtek,snd_hda_codec_si3054,snd_hda_codec_generic,snd_hda_codec,snd_hda_intelsnd_hwdep 16384 1 snd_hda_codecsnd_pcm 86016 4 snd_hda_codec_si3054,snd_hda_codec,snd_hda_intel,snd_hda_coresnd 65536 18 snd_hda_codec_realtek,snd_hda_codec_si3054,snd_hwdep,snd_timer,snd_pcm,snd_hda_codec_generic,snd_hda_codec,snd_hda_intel For completeness, this is my pulseaudio config (I have not tried meddling with it): $ pulseaudio --dump-conf### Read from configuration file: /etc/pulse/daemon.conf ###daemonize = nofail = yeshigh-priority = yesnice-level = -11realtime-scheduling = yesrealtime-priority = 5allow-module-loading = yesallow-exit = yesuse-pid-file = yessystem-instance = nolocal-server-type = usercpu-limit = noenable-shm = yesflat-volumes = nolock-memory = noexit-idle-time = 20scache-idle-time = 20dl-search-path = /usr/lib/pulse-9.0/modulesdefault-script-file = /etc/pulse/default.paload-default-script-file = yeslog-target = log-level = noticeresample-method = autoenable-remixing = yesenable-lfe-remixing = nolfe-crossover-freq = 0default-sample-format = s16ledefault-sample-rate = 44100alternate-sample-rate = 48000default-sample-channels = 2default-channel-map = front-left,front-rightdefault-fragments = 4default-fragment-size-msec = 25enable-deferred-volume = yesdeferred-volume-safety-margin-usec = 8000deferred-volume-extra-delay-usec = 0shm-size-bytes = 0log-meta = nolog-time = nolog-backtrace = 0rlimit-fsize = -1rlimit-data = -1rlimit-stack = -1rlimit-core = -1rlimit-rss = -1rlimit-as = -1rlimit-nproc = -1rlimit-nofile = 256rlimit-memlock = -1rlimit-locks = -1rlimit-sigpending = -1rlimit-msgqueue = -1rlimit-nice = 31rlimit-rtprio = 9rlimit-rttime = 200000 As per Faheem Mitha's comment, I'm confident the pulseaudio tmpfs has the right permissions: # ls -la /run/user/861213/pulse/total 4drwx------ 2 grochmal users 80 Jul 4 21:44 .drwx------ 5 grochmal users 120 Jul 4 21:46 ..srw-rw-rw- 1 grochmal users 0 Jul 4 21:44 native-rw------- 1 grochmal users 4 Jul 4 21:44 pid And pavucontrol was muted. I was not aware of pavucontrol which resulted in the issue in the first place: Question I'm out of ideas. I believe that the Loopback audio interface exists in kernel space , therefore my problem is that I cannot bring the microphone data into user space . Yet, I'm not 100% sure of it. What other options can I give to snd-hda-intel (or the other modules) that might be relevant for a microphone that works on the loopback interface but does not propagate to the application layer? Could I be doing something wrong with pulseaudio ? But then again, pulseaudio worked correctly (together with alsa ) for all that time, and I use audacity quite often.
Based on correspondence with the poster (see comments), it turned out that the sound card was muted inside pavucontrol .
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/293876", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/172635/" ] }
293,898
On my main machine, a MacBook Pro, I have a .bash_profile file that I'd like to use unaltered on my Dreamhost linux machine. However, there's a few lines that are only applicable to macOS, such as alias mvim="/Applications/MacVim.app/Contents/MacOS/MacVim" . Is there a way in bash to test for whether it's running under macOS or Debian (or just not macOS) and only execute that above line, and a few others, when running under macOS? Whereas other questions here address how to find out which Linux distro is being used, here I only need to know if I'm running on macOS or Linux, and the solutions for knowing the Linux distro aren't available on macOS.
if [[ $(uname -s) == Linux ]]then doThiselse doThatfi
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/293898", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/74293/" ] }
293,906
I need to acquire data from a little computer (Red Pitaya-linux) and save it to an external PC because it is very large. Also, I do not want to save the file first and then copy it using ssh for the same reason. Should I insert a ssh into the acquire script?
if [[ $(uname -s) == Linux ]]then doThiselse doThatfi
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/293906", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/178148/" ] }
293,940
I'm making a script to install my theme, after it finished installing it will appear the changelog and there will be "Press any key to continue" so that after users read the changelog then press any key to continue
You can use the read command. If you are using bash : read -p "Press enter to continue" In other shells, you can do: printf "%s " "Press enter to continue"read ans As mentioned in the comments above, this command does actually require the user to press enter ; a solution that works with any key in bash would be: read -n 1 -s -r -p "Press any key to continue" Explanation by Rayne and wchargin -n defines the required character count to stop reading -s hides the user's input -r causes the string to be interpreted "raw" (without considering backslash escapes)
{ "score": 10, "source": [ "https://unix.stackexchange.com/questions/293940", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/177727/" ] }
293,951
man synopsis for scp is: scp [-1246BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file] [-l limit] [-o ssh_option] [-P port] [-S program] [[user@]host1:]file1 ... [[user@]host2:]file2 What is source, what is target? I'm always wondering in which direction the copying takes place. How is it defined?
Unix commands almost always (with very few exceptions) have source before target. And most allow multiple sources before the final target if it makes sense to do so. That includes scp . Some commands (like the GNU versions of cp and mv ) have an option (e.g. -t or --target-directory=DIRECTORY ) that allow you to put the target first - but the default is the standard "source(s) before target" . This is mostly useful so you can have the target before the source when using something like find ... -exec cp -t target/ {} + , or so you can avoid using -I {} with xargs (which is much slower, it causes xargs to fork one command per arg, rather than fit as many as it can on each command line), e.g. ... | xargs -0r mv -t target/ instead of ... | xargs -0r -I {} mv {} target/ Without an explicit override option as mentioned above, "target before source" is almost unheard of - so rare that you're fully entitled to think "Huh? WTF?" if you ever encounter it. If you need to scp multiple files to multiple machines at once, do it in a for loop like this: for h in host1 host2 host3... ; do scp file1 file2 file3... "user@$h:/path/"done Or use pdcp from Parallel Distributed Shell . pdsh is packaged for most linux distributions. e.g. pdcp -w host1,host2,host3 file1 file2 file3 /path/to/target/ That's a very simple example, pdsh has a config file you can use to define hosts and groups of hosts with arbitrary group names (e.g. all , webservers , dbservers , gpunodes , or whatever). You can then use them in pdsh or pdcp commands: pdsh -g all 'uname -a ; uptime'pdcp -g webservers index.html /var/www/ Unlike the for loop above, it doesn't run commands or copy the files sequentially, one host at a time. It runs multiple commands in parallel, with reasonable limits based on the number of CPU cores your machine has.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/293951", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/79043/" ] }
293,966
My log files are getting dumped with following message while running shell scripts using some underlying MySQL commands. Here is the message: "Warning: Using a password on the command line interface can be insecure." To stop these messages, I am using the following job definition. Example: run_wrapper.sh |grep -v "Warning: Using a password" > output.log 2>&1 This worked but the MySQL errors are not being logged to output.log . If I change the definition like the following, then MySQL errors start appearing if any run_wrapper.sh > output.log 2>&1 So the question is how to suppress the warning messages and also report SQL errors in log files using only the cron definition?
In your bash script, edit it at top export MYSQL_PWD=yourdbpassword and mysql query like: mysql -u username -h host db -e "statement" Reference: From answer posted at Stackoverflow . Other answers can also be followed.
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/293966", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/178196/" ] }
293,969
Their approach https://wiki.debian.org/InstallingDebianOn/Apple/MacBookAir/3-2 does not work(everything goes fine but usb does not become bootable).It also seems seems several years old and outdated. Other distos have large amouts of troubleshooting this issue, but not debian. Any advice how can I debug why my usb did not becamse Debian bootable after those procedures. My steps were: 1)erase usb drive using disk utils and create FAT partition(i tried also exFAT and OSX Extended). 2) downloaded the iso and converted it to img: hdiutil convert debian-8.4.0-i386-DVD-1.iso -format UDRW -o debian-8.4.0-i386-DVD-1.img and renaming the result to remove the ".img" from name. I also tried to us UDTO instead of UDRW. 3) finding my usb location using diskutil list, it was /dev/disk2 4) unmounting the usb: diskutil unmountDisk /dev/disk2 5) dding the image: sudo dd if=debian-8.4.0-i386-DVD-1.img of=/dev/disk2 bs=1m what took several hours. The result was the expected message that usb could not be read. 6) ejecting the usb with: diskutil eject /dev/disk2 The result was that the usb was not bootable - in the loading screen pressing alt button - the usb does not show.
I didn't convert the ISO to img, I just formatted a USB drive for FAT and used dd : sudo diskutil unmountdisk /dev/disk1sudo dd if=./debian.iso of=/dev/disk1 bs=1m I tested this with Debian 9. It's important to note that the appropriate /dev/disk# should be determined by using the following command on the macOS command line: diskutil list In the question above, the USB device mapped to /dev/disk2 whereas the example above uses /dev/disk1 . But the number could be 3 or 4 or some other number. Ensure the number correlates with the memory stick you use; you risk losing data if you get it wrong.
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/293969", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/176316/" ] }
293,982
I have Linux Mint 17.3 Rosa installed on my PC. Now since Mint 18 was released I thought I could upgrade easy and execute do-release-upgrade . I have done this in Ubuntu for that past few years. But to my surprise there is no command like that on Linux Mint. Can I upgrade my system to Mint 18 or do I need to make a clean install? (A clean install is no option for me. I don't have so much time at work that I can setup my whole OS from scratch)
Seems that the normal do-release-upgrade thing has been replaced by a smarter script. Try sudo apt-get install mintupgrade mintupgrade checkmintupgrade downloadmintupgrade upgrade
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/293982", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/178203/" ] }
293,987
How can I log in with the su command in one line in the terminal? I know that the sudo command can do that: echo [password] | sudo -S [command] But when I try to imply it in the su command : echo [password] | su [username] I get an error: standard in must be tty I don't have access to the sudo account (so I can't access and edit the sudoers file). I know that the right syntax is basically: su [username] What I want to do is to add a su command to aliases without being needed to enter password every time
Seems that the normal do-release-upgrade thing has been replaced by a smarter script. Try sudo apt-get install mintupgrade mintupgrade checkmintupgrade downloadmintupgrade upgrade
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/293987", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/178215/" ] }
294,005
I am trying to move 7th column of my csv file to the end by using awk -F '{print $1,$2,$3,$4,$5,$6,$8,$9,$10,$11,$7}',OFS= "$file" where $file is a .csv file in a directory. However, the output is awk: ^ syntax error Does anyone know how to fix this error?
The -F option needs an argument (field separator): -F, for example. The end of the awk script must be separated with a (space char) with the rest of the parameters. If the field separator is , and you wish to keep it, and if the number of column is constant and lower than or equal to 11, give a try to this: awk -F, '{print $1,$2,$3,$4,$5,$6,$8,$9,$10,$11,$7}' OFS=, "$file" If your field separator is a semicolon don't forget to set it in quotes like so awk -f';' '{print $1,$2,$3,$4,$5,$6,$8,$9,$10,$11,$7}' OFS=';' "$file"
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/294005", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/172771/" ] }
294,066
Consider the file tmp.txt whose contents are: xabcd I want to open it in VIM and move cursor to the c character.So I run VIM with the arguments: $ vim -c "/c" tmp.txt But it sets the cursor on a . It looks like VIM was able to find c but placed the cursor at the line begin. Why does it work different if I execute /c in VIM normal mode when file is open?
You can position the cursor on the first match using the -s (script) option. According to the vim manual : -s {scriptin} The script file {scriptin} is read. The characters in the file are interpreted as if you had typed them. The same can be done with the command " :source! {scriptin} ". If the end of the file is reached before the editor exits, further characters are read from the keyboard. You could use a temporary file with the keystrokes, or even (if you are using bash ) process substitution. For example: #!/bin/bashvim -s <(printf '/c\n') tmp.txt This approach works with more complicated searches than a single character.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/294066", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/163956/" ] }
294,089
A bash script that contains for i in {a,b}-{1,2}; do echo $i;done prints a-1a-2b-1b-2 when executed. This is what I expected - as the {a,b} construct is expanded. However, when (another) script contains v={a,b}-{1,2}echo $v it prints {a,b}-{1,2} which is not what I expected. I expected it to print a-1 a-2 b-1 b-2 . Obviously, the {a,b} construct is not expanded. I can make it expand like so v=$(echo {a,b}-{1,2}) Based on these observations I have two questions: 1) when is the {a,b} construct expanded? 2) is $(echo {a,b}-{1,2}) the preferred way to trigger an expansion when required?
The Bash manual says that: SIMPLE COMMAND EXPANSIONWhen a simple command is executed, the shell performs the followingexpansions, assignments, and redirections, from left to right.[...]4. The text after the = in each variable assignment undergoes tilde expansion, parameter expansion, command substitution, arithmetic expansion, and quote removal before being assigned to the variable. Brace expansion is not in the list, so it isn't performed for the assignment v={a,b}-{1,2} . As mentioned by @Wildcard, the simple expansion to v=a-1 v=b-1 ... would be senseless anyway. Also, when executing the echo $v , the following applies: EXPANSIONExpansion is performed on the command line after it has been splitinto words. [...]The order of expansions is: brace expansion; tilde expansion, parameter and variable expansion, arithmetic expansion, and commandsubstitution (done in a left-to-right fashion); word splitting; andpathname expansion. Brace expansion happens before variable expansion, so the braces assigned to $v aren't expanded. But you can do stuff like this: $ var_this=foo var_that=bar$ echo $var_{this,that}foo bar Expanding it with $(echo ...) should work if you don't have any whitespace in the string to be expanded, and hence won't run into problems with word splitting. A better way might be to use an array variable if you can. e.g. save the expansion into an array and run some command with the expanded values: $ v=( {a,b}-{1,2} )$ some_command "${v[@]}"
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/294089", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/6479/" ] }
294,128
I have a file with many lines. I want to delete from the line 1458 to the end of the file. I think that I can do it with sed , but I do not know how to.
sed '1458,$d' You can use that with -i to edit the file in place if necessary. e.g sed -i '1458,$d' filename.txt
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/294128", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/152587/" ] }
294,145
I have 2 large files (3000 columns, 15000 rows) of the following format file1 (tab-separated): 1/0 0/0 0/00/0 1/1 0/01/1 0/1 0/0 file2 (tab-separated): 3 5 21 7 103 4 3 I'd like to combine the values from the first column of each file with a ":" separator, then move on to the second, third, etc. columns. Desired output (tab-separated): 1/0:3 0/0:5 0/0:20/0:1 1/1:7 0/0:101/1:3 0/1:4 0/0:3 Efficiency isn't critical, so any language is fine. I apologize if this has been asked before.
Something like this? Worked with your sample data: paste file{1,2} | awk '{for (i=1;i<=NF/2; i++){printf "%s:%s\t",$i,$(NF/2+i)};printf "\n"}'1/0:3 0/0:5 0/0:20/0:1 1/1:7 0/0:101/1:3 0/1:4 0/0:3
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/294145", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/178329/" ] }
294,180
If I disable memory overcommit by setting vm.overcommit_memory to 2 , by default the system will allow to allocate the memory up to the dimension of swap + 50% of physical memory, as explained here . I can change the ratio by modifying vm.overcommit_ratio parameter.Let's say I set it to 80%, so 80% of physical memory may be used. My question are: what the system will do with the remaining 20%? why is this parameter required in first place? why I should not always set it to 100%?
What the system will do with the remaining 20%? The kernel will use the remaining physical memory for its own purposes (internal structures, tables, buffers, caches, whatever). The memory overcommitment setting handle userland application virtual memory reservations, the kernel doesn't use virtual memory but physical one. Why is this parameter required in first place? The overcommit_ratio parameter is an implementation choice designed to prevent applications to reserve more virtual memory than what will reasonably be available for them in the future, i.e. when they actually access the memory (or at least try to). Setting overcommit_ratio to 50% has been considered a reasonable default value by the Linux kernel developers. It assumes the kernel won't ever need to use more than 50% of the physical RAM. Your mileage may vary, the reason why it is a tunable. Why I should not always set it to 100%? Setting it to 100% (or any "too high" value) doesn't reliably disable overcommitment because you cannot assume the kernel will use 0% (or too little) of RAM. It won't prevent applications to crash as the kernel might preempt anyway all the physical memory it demands.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/294180", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/178368/" ] }
294,242
Can I use getopts for parsing command-line arguments in my bash scripts(not sh ) without worrying about another depedency?
$ type getoptsgetopts is a shell builtin getopts is built in, so it's present anywhere bash is. To be sure of that you'd need to check the bash documentation to see whether it's an optional feature — it isn't. More precisely, this tells you that getopts is available in this particular version of bash. You need to check the release notes for older versions to see when getopts was introduced; that happened before the dawn of time (it was already present in bash 1.14 and you'd have a hard time finding a version that old). Even better, you can count on getopts even in shells that aren't bash, since it's required by POSIX .
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/294242", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/151955/" ] }
294,299
Linux does not (yet) follow the POSIX.1 standard which says that a renice on a process affects "all system scope threads in the process", because according to the pthreads(7) doc "threads do not share a common nice value". However, sometimes, it can be convenient to renice "everything" related to a given process (one example would be Apache child processes and all their threads). So, how can I renice all threads belonging to a given process ? how can I renice all child processes belonging to a given process ? I am looking for a fairly easy solution. I know that process groups can sometimes be helpful, however, they do not always match what I want to do: they can include a broader or different set of processes. Using a cgroup managed by systemd might also be helpful, but even if I am interested to hear about it, I mostly looking for a "standard" solution. EDIT: also, man (7) pthreads says "all of the threads in a process are placed in the same thread group; all members of a thread group share the same PID". So, is it even possible to renice something which doesn't have it's own PID?
You can use /proc/$PID/task to find all threads of a given process, therefore you can use $ ls /proc/$PID/task | xargs renice $PRIO to renice all threads belonging to a given process. Same way /proc/$PID/task/$PID/children can be used to find all child processes (or /proc/$PID/task/*/children if you want all child processes of all threads of a given process). $ cat /proc/$PID/task/$PID/children | xargs renice $PRIO$ cat /proc/$PID/task/*/children | xargs renice $PRIO
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/294299", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/30196/" ] }
294,300
My postfix e-mail server is finally working well. Now, I need to prevent users from forging their e-mail addresses in the client programs in the "from" field in the header, because a user can send email as other user with that, and a unexperienced user can think that is real. If a user is experienced, he can inspect the email headers and know what is happening, but is there a way to block this behaviour?
Have a look at the smtpd_sender_restrictions and smtpd_sender_login_maps settings. The former can prevent malformed from addresses, while the latter can force the sender address to match the login name. # Prevent malformed senderssmtpd_sender_restrictions = reject_non_fqdn_sender # Ensure correct mail addresses reject_unknown_sender_domain # Ensure sender address is from an existing domain reject_authenticated_sender_login_mismatch # Check if the user is # allowed to use this sender address# Maps used to stop sender address forgeries.smtpd_sender_login_maps = pcre:/etc/postfix/login_maps.pcre The contents of login_maps.pcre could be # Use this regex if your users are local users, i.e. if the login name# is just the username, not a full mail address.# Note that literal dots have to be backslash escaped (`\.`) to avoid# interpretation of these dots as regex wildcard./^([^@+]*)(\+[^@]*)?@example\.com$/ ${1}# If one doesn't care about subaddresses, this could be simplified to/^(.*)@example\.com/ ${1}# This is appropriate if you have virtual users who login with their# full mail address as their username. Local addresses won't work, though/^(.*)$/ ${1} The above config assumes that postfix was compiled with support for PCRE. On Ubuntu/Debian, this requires the postfix-pcre package to be installed. Note that this will only work if nobody but authenticated users can send mail. If you allow mail from unauthenticated users, the above method won't help and will fail. Make sure to read Rui F Ribeiro's answer if that's the case.
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/294300", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/170792/" ] }
294,337
Since URxvt 9.20, text can be copied to the clipboard with Ctrl + Alt + C (and also pasted from with Ctrl + Alt + V ). But, I already use these bindings for another thing. So how can I rebind, in URxvt >=9.20 it to Ctrl + Shift + C (and Ctrl + Shift + V for paste) ?
The eval extension shipped with rxvt-unicode has paste_clipboard and selection_to_clipboard actions for this, that can be bound to any keysym (see here ). In your .Xresources add: URxvt.keysym.Shift-Control-V: eval:paste_clipboardURxvt.keysym.Shift-Control-C: eval:selection_to_clipboard To disable the previous keybindings, you'll also need: URxvt.keysym.Control-Meta-c: builtin-string:URxvt.keysym.Control-Meta-v: builtin-string: You can reload the file with: xrdb -load .Xresources You'll need to restart rxvt for the changes to take effect.
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/294337", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/56505/" ] }
294,341
I have a directory of jpg images. Is there a shell script ( bash or zsh would be acceptable) that would move all landscape images into a directory, and all portrait images into another directory?
You could use imagemagick 's identify with the fx special operator to compare height and width e.g. check h/w ratio: for f in ./*.jpgdo r=$(identify -format '%[fx:(h/w)]' "$f") if (( r > 1 )) then mv "$f" /path/to/portraits elif (( r < 1 )) then mv "$f" /path/to/landscapes fidone# mv ./*.jpg /path/to/squares This leaves the square images in the current directory. Uncomment the last line to move them to their own directory. Or, if you wanted to include them to either landscapes or portraits, change one of the comparison operators to either <= or >= .
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/294341", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/92593/" ] }
294,371
I started learning Bash a couple of days ago. I'm trying to obtain an exit status of grep expression into a variable like this: check=grep -ci 'text' file.sh and the output that I got is No command '-ic' found Should I do it with a pipe command?
Your command, check=grep -ci 'text' file.sh will be interpreted by the shell as "run the command -ci with the arguments text and file.sh , and set the variable check to the value grep in its environment". The shell stores the exit value of most recently executed command in the variable ? . You can assign its value to one of your own variables like this: grep -i 'PATTERN' filecheck=$? If you want to act on this value, you may either use your check variable: if [ "$check" -eq 0 ]; then # do things for successelse # do other things for failurefi or you could skip using a separate variable and having to inspect $? all together: if grep -q -i 'pattern' file; then # do things (pattern was found)else # do other things (pattern was not found)fi (note the -q , it instructs grep to not output anything and to exit as soon as something matches; we aren't really interested in what matches here) Or, if you just want to "do things" when the pattern is not found: if ! grep -q -i 'pattern' file; then # do things (pattern was not found)fi Saving $? into another variable is only ever needed if you need to use it later, when the value in $? has been overwritten, as in mkdir "$dir"err=$?if [ "$err" -ne 0 ] && [ ! -d "$dir" ]; then printf 'Error creating %s (error code %d)\n' "$dir" "$err" >&2 exit "$err"fi In the above code snippet, $? will be overwritten by the result of the [ "$err" -ne 0 ] && [ ! -d "$dir" ] test. Saving it here is really only necessary if we need to display it and use it with exit .
{ "score": 6, "source": [ "https://unix.stackexchange.com/questions/294371", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/178555/" ] }
294,378
I'm trying to perform environment variable replacement through envsubst , but I want to only replace specific variables. From the docs I should be able to tell envsubst to only replace certain variables but I'm failing to be able to do that. For example, if I have a file containing: VAR_1=${VAR_1}VAR_2=${VAR_2} how should I execute envsubst so that it only replaces the reference to ${VAR_1} ?
Per the man page: envsubst [OPTION] [SHELL-FORMAT] If a SHELL-FORMAT is given, only those environment variables thatare referenced in SHELL-FORMAT are substituted; otherwise allenvironment variables references occurring in standard input aresubstituted. Where SHELL-FORMAT strings are "strings with references to shell variables in the form $variable or ${variable} [...] The variable names must consist solely of alphanumeric or underscore ASCII characters, not start with a digit and be nonempty; otherwise such a variable reference is ignored." . Note that the format ${VAR:-default} is not supported. I mentioned HERE some alternatives that support it along with other features. Anyway, back to gettext envsubst : So, one has to pass the respective variables names to envsubst in a shell format string (obviously, they need to be escaped/quoted so as to be passed literally to envsubst ). Example: input file e.g. infile : VAR1=${VAR1}VAR2=${VAR2}VAR3=${VAR3} and some values like export VAR1="one" VAR2="two" VAR3="three" then running envsubst '${VAR1} ${VAR3}' <infile or envsubst '${VAR1},${VAR3}' <infile or envsubst '${VAR1}${VAR3}' <infile outputs VAR1=oneVAR2=${VAR2}VAR3=three Or, if you prefer backslash: envsubst \$VAR1,\$VAR2 <infile produces VAR1=oneVAR2=twoVAR3=${VAR3}
{ "score": 8, "source": [ "https://unix.stackexchange.com/questions/294378", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/178562/" ] }
294,386
I am following a tutorial in computational microbiology: William Lindstrom, Garrett M. Morris, Christoph Weber, and Ruth Huey (2008-01-29). Using AutoDock 4 for Virtual Screening . Scripps Research Institute. On page 10 there is ex01.csh which contains (original unindented, indentation added by StackExchange participants): foreach f (tmp*) echo $f set zid = `grep ZINC $f` if !(-e "$zid".mol2) then set filename = "$zid".mol2 else foreach n (`seq –w 1 99`) if !(-e "$zid"_"$n".mol2) then set filename = "$zid"_"$n".mol2 break endif end endif mv –v $f $filenameend I want to run the above command. I have been trying to figure it out for the last 2 days but have failed. Every time, at the first step, which is foreach f (tmp*) it says bash : syntax near unexpected error '(' I know zero about linux stuff, and am just following what I see in the tutorial. How i can fix my problem?
Per the man page: envsubst [OPTION] [SHELL-FORMAT] If a SHELL-FORMAT is given, only those environment variables thatare referenced in SHELL-FORMAT are substituted; otherwise allenvironment variables references occurring in standard input aresubstituted. Where SHELL-FORMAT strings are "strings with references to shell variables in the form $variable or ${variable} [...] The variable names must consist solely of alphanumeric or underscore ASCII characters, not start with a digit and be nonempty; otherwise such a variable reference is ignored." . Note that the format ${VAR:-default} is not supported. I mentioned HERE some alternatives that support it along with other features. Anyway, back to gettext envsubst : So, one has to pass the respective variables names to envsubst in a shell format string (obviously, they need to be escaped/quoted so as to be passed literally to envsubst ). Example: input file e.g. infile : VAR1=${VAR1}VAR2=${VAR2}VAR3=${VAR3} and some values like export VAR1="one" VAR2="two" VAR3="three" then running envsubst '${VAR1} ${VAR3}' <infile or envsubst '${VAR1},${VAR3}' <infile or envsubst '${VAR1}${VAR3}' <infile outputs VAR1=oneVAR2=${VAR2}VAR3=three Or, if you prefer backslash: envsubst \$VAR1,\$VAR2 <infile produces VAR1=oneVAR2=twoVAR3=${VAR3}
{ "score": 8, "source": [ "https://unix.stackexchange.com/questions/294386", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/178566/" ] }
294,486
I have a file called file.txt . How can I print the first line only using the grep command?
Although it's an unconventional application of grep, you can do it in GNU grep using grep -m1 "" file.txt It works because the empty expression matches anything, while -m1 causes grep to exit after the first match -m NUM, --max-count=NUM Stop reading a file after NUM matching lines.
{ "score": 6, "source": [ "https://unix.stackexchange.com/questions/294486", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/178651/" ] }
294,517
Other than the obvious syntactical point that b can accept a label while n does not, and that to use b without a label you need to place it at the end of an argument passed with -e (for one-liners, at least)...a b without a label and an n seem to do the exact same thing. Is this actually true, or are there subtle differences I haven't noticed? What are the conditions under which they do the same thing and the conditions under which they don't?
Well, let's see... the b ranch command: [2addr]b[label] Branch to :label. If label is not specified, branch to the end of the script. the n ext command: [2addr]n If auto-print is not disabled, print the pattern space, then, regardless, replace the pattern space with the next line of input. If no next line of input is available, branch to the end of the script. So the main difference here is: b unconditionally branches to the end of script n only branches to the end of script if there's no more input Assuming an input like: fduefourfourfduefour and that I wanted to replace f with t but only on lines that match four and on all other lines replace u with i . One way to do this is sed '/four/{s/f/t/;b;};s/u/i/' infile and the output is, as expected fdietourtourfdietour now, let's see what happens when using n instead of b : fdietourfoirfdietour The second line matching four was edited to foir instead of tour for the simple reason n does not return to the top of the script. Instead, the s command following the n processed the line even thought this was not intended. However, on the last line, only the 1st substitution was made so the s command after the n was no longer executed. To sum up, these two commands could be functionally equivalent if: the script was processing the last line of input ( before executing n ) or the next line pulled in by n was not supposed to be edited by the commands that precede n 1 anyway (in other words, the next line was not an address that's associated to b ) It's true that n prints the current pattern space and pulls in the next line but b alone also has the same effect: branching to end of script means auto-printing (unless sed was invoked with -n , in which case n doesn't print either) and then automatically reading in the next line of input. The main difference, as I said, is that n doesn't jump to end of script (and it doesn't return to top of the script either): sed simply executes the remaining commands - if any ( and if not on the last line ). 1 Those commands won't be executed since, as I said, n doesn't return to the top of the script; also, the remaining commands might edit the line which is something that wasn't supposed to happen.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/294517", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/135943/" ] }
294,544
Disclaimerish thingy: I just went through the list oft StackExchange sites for about 20 minutes trying to figure out where to post this. If you know any site more suitable, please move this question there. I'm posting this here because unix time got me thinking. So as we all know, there is unix time and there is UTC. Unix time just keeps on ticking, counting seconds – one second per second –, whereas UTC tries to keep time in the human-readable formats we use aligned with Earth's phase in its rotation. To do this, UTC inserts leap seconds from time to time. Since time is relative to gravitational force the object experiencing time is exposed to, other kinds of acceleration, and relative speed, this leads to 2 questions. Let's get over the simple one first: Where is unix time measured? If Alice and Bob start out agreeing the current time is 1467932496.42732894722748 when they are at the same place (a second of course being defined as 9'192'631'770 cycles of radiation corresponding to the transition between two energy levels of the caesium-133 atom at rest and at 0 K), experience a twin paradox due to Alice living on sea level and Bob living high up in the mountains or Alice living at the north pole and Bob living at the equator, they won't agree any more. So how is unix time defined precisely? You might not see the problem with UTC at first because surely everyone can agree on when earth completed an orbit (this is of course ignoring continental plate movement but I think we get that one figured out pretty well because with GPS it's possible to measure their movement very precisely and we can assume them to be on a set position in our model and not move as continental plates shift), no matter whether they are on a mountain, on sea level, on the equator, or at the north pole. There might be some time differences but they don't accumulate. But a second is defined as 9'192'631'770 cycles of radiation corresponding to the transition between two energy levels of the caesium-133 atom at rest and at 0 K and caesium-133 atom don't care about earth's orbit. So UTC decides where to insert a leap second but there has to be a measured or predicted shift between the phase of earth's orbit and the time measured somewhere by an atomic clock. Where is that somewhere?
Your headline question doesn't have a real answer; Unix time isn't a real timescale, and isn't "measured" anywhere. It's a representation of UTC, albeit a poor one because there are moments in UTC that it can't represent. Unix time insists on there being 86,400 seconds in every day, but UTC deviates from that due to leap seconds. As to your broader question, there are four important timescales of interest: UT1 (Universal Time), which is calculated by observatories around the world which measure the rotation of the Earth with respect to the fixed stars. With these observations and a little math, we get a more modern version of the old Greenwich Mean Time, which was based on the moment of solar noon at the Royal Observatory in Greenwich. Universal Time is calculated by An organization called the IERS (the International Earth Rotation and Reference Systems Service, formerly the International Earth Rotation Service). TAI (International Atomic Time), which is kept by hundreds of atomic clocks around the world, maintained by national standards bodies and such. The keepers of the clocks that contribute to TAI use time transfer techniques to steer their clocks towards each other, canceling out any small errors of individual clocks and creating an ensemble time; that ensemble is TAI, published by the International Bureau of Weights and Measures (BIPM), the stewards of the SI system of units. To answer your question about time dilation, TAI is defined to be atomic time at sea level (actually, at the geoid, which is a fancier version of the same idea), and each clock corrects for the effects of its own altitude. UTC (Coordinated Universal Time), which was set equal to ten seconds behind TAI on 1 January 1972, and since that date it ticks forwards at exactly the same rate as TAI, except when a leap second is added or subtracted. The IERS makes the decision to announce a leap second in order to keep the difference within 0.9 seconds (in practice, within about 0.6 seconds; an added leap second causes the difference to go from −0.6 to +0.4). In theory, leap seconds can be both positive and negative, but because the rotation of the earth is slowing down compared to the standard established by SI and TAI, a negative leap second has never been necessary and probably never will. Unix time , which does its best to represent UTC as a single number. Every Unix time that is a multiple of 86,400 corresponds to midnight UTC. Since not all UTC days are 86,400 seconds long, but all "Unix days" are, there is an irreconcilable difference that has to be patched over somehow. There's no Unix time corresponding to an added leap second. In practice, systems will either act as though the previous second occurred twice (with the unix timestamp jumping backwards one second, then proceeding forward again), or apply a technique like leap smearing that warps time for a longer period of time on either side of a leap second. In either case there's some inaccuracy, although at least the second one is monotonic. In both cases, the amount of time that passes between two distant Unix timestamps a and b isn't equal to b − a ; it's equal to b − a plus the number of intervening leap seconds . Since UT1, TAI, UTC, and the IERS are all worldwide, multinational efforts, there is no single "where", although IERS bulletins are published from the Paris Observatory and the BIPM is also based in Paris, that's one answer. An organization that requires precise, traceable time might state their timebase as something like "UTC(USNO)", which means that their timestamps are in UTC and that they're derived from the time at the US Naval Observatory, but given the problems that I mentioned with Unix time, it's basically incompatible with that level of precision—anyone dealing with really precise time will have an alternative to Unix time.
{ "score": 6, "source": [ "https://unix.stackexchange.com/questions/294544", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/147785/" ] }
294,600
So I'm following a tutorial to install OTRS which is Open source Ticket Request System. So in order to install, it requires: 4GB of Swap space. Here's the command I used: [root@ip-10-0-7-41 ~]# df -hFilesystem Size Used Avail Use% Mounted on/dev/xvda1 50G 14G 37G 27% /devtmpfs 478M 0 478M 0% /devtmpfs 496M 0 496M 0% /dev/shmtmpfs 496M 13M 484M 3% /runtmpfs 496M 0 496M 0% /sys/fs/cgrouptmpfs 100M 0 100M 0% /run/user/1000[root@ip-10-0-7-41 ~]# fallocate -l 4G /myswap[root@ip-10-0-7-41 ~]# ls -lh /myswap-rw-r--r--. 1 root root 4.0G Jul 8 08:44 /myswap[root@ip-10-0-7-41 ~]# chmod 600 /myswap[root@ip-10-0-7-41 ~]# mkswap /myswapSetting up swapspace version 1, size = 4194300 KiBno label, UUID=3656082a-148d-4604-96fb-5b4604fa5b2e[root@ip-10-0-7-41 ~]# swapon /myswapswapon: /myswap: swapon failed: Invalid argument You can see : Invalid argument error here. I tried many time in vain to enable it.Someone please tell me how to fix this error.(I'm running this CentOS 7 on AWS Instance EC2) [root@ip-10-0-7-41 ~]# df -T | awk '{print $1,$2,$NF}' | grep "^/dev"/dev/xvda1 xfs /
The problem with fallocate(1) is that it uses filesystem ioctls to make the allocation fast and effective, the disadvantage is that it does not physically allocate the space but swapon(2) syscall requires a real space.Reference : https://bugzilla.redhat.com/show_bug.cgi?id=1129205 I'd faced this issue earlier with my box too. So instead of using fallocate , I used dd as the link suggests sudo dd if=/dev/zero of=/myswap count=4096 bs=1MiB and moving ahead with chmod , mkswap & swapon commands. Bingo ! It worked.
{ "score": 8, "source": [ "https://unix.stackexchange.com/questions/294600", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/138782/" ] }
294,625
I have a command which outputs lots of data (say, strace with lots of syscalls, running for a few minutes). Is there any option (e.g. command wrapper or something similar) that would allow me to pause the output of the command (just the output on the screen, I don't mind the command running in the background), then unpause it after I take a look on its output?
You have three options: press control S to stop output, control Q to resume (this is called XON/XOFF) redirect your output to a pager such as less , e.g., strace date | less redirect your output to a file, e.g., strace -o foo date , and browse it later.
{ "score": 6, "source": [ "https://unix.stackexchange.com/questions/294625", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/20334/" ] }
294,627
I have seen that people use ls -alh in the Linux terminal. However, when I see the manual, I don't see -alh (i.e. when I type man ls ). Why do I not have it in the manual? Can someone explain what it does?
ls -alh is the same as ls -a -l -h . Multiple short options can be combined like this. Here are the meanings of those options from man ls : -a, --all do not ignore entries starting with . -l use a long listing format -h, --human-readable with -l, print sizes in human readable format (e.g., 1K 234M 2G)
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/294627", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/176824/" ] }
294,667
I have a file called test similar to the following: hellomyname<h6>test morning</h6>isbob I know I would use: sed -i -- 's/name//g' test To remove name from the file, but how do I remove <h6>test morning</h6> ? The string could be anywhere in the file and the file could be anything like a .css or .html file.
For such cases you can use any character instead / . For example sed -i 's|<h6>test morning</h6>||g' test For string mach patterns you should escape first one sed -i '\|<h6>test morning</h6>|s///g' test If you have few / in the pattern may be easy to escape it directly sed -i '/<h6>test morning<\/h6>/s///g' test
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/294667", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/117923/" ] }
294,676
When using df -h | grep /dev/root | awk '{print $5}' I get the usage of my SD Card in my Pi: 78% But when I use /usr/bin/ssh -i /path/to/key user@server "df -h | grep /dev/root | awk '{print $5}'" from another computer, I get: /dev/root 7.2G 5.3G 1.6G 78% / Full df -h : Filesystem Size Used Avail Use% Mounted on/dev/root 7.2G 5.3G 1.6G 78% /devtmpfs 364M 0 364M 0% /devtmpfs 368M 68K 368M 1% /dev/shmtmpfs 368M 5.2M 363M 2% /runtmpfs 5.0M 4.0K 5.0M 1% /run/locktmpfs 368M 0 368M 0% /sys/fs/cgroup/dev/mmcblk0p1 60M 21M 40M 35% /boottmpfs 74M 4.0K 74M 1% /run/user/1000
You're hitting a quoting problem; the $5 is being interpreted at the wrong time. There are at least two solutions: Put a \ before the $ ; e.g. /usr/bin/ssh -i /path/to/key user@server "df -h | grep /dev/root | awk '{print \$5}'" Run the df remotely but the grep and awk locally. e.g. /usr/bin/ssh -i /path/to/key user@server df -h | grep /dev/root | awk '{print $5}' FWIW, I'd run a version of the second option but merging grep and awk /usr/bin/ssh -i /path/to/key user@server df -h | awk '/\/dev\/root/ {print $5}'
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/294676", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/166118/" ] }
294,710
I need to delete the last line of gz file without uncompressing.The file has 500 lines. How can I do that? I have tried: gzip -dc "$files" | tail -500 | gzip -c > "$files".tmp But It doesn´t works.
You can't modify a compressed file without decompressing it. At the very least, to delete all text after the 499th line, you have to decompress the first 499 lines to find where the 499th line ends. If you want to delete the last line regardless of how many lines there are, you need to decompress the whole file to identify where the last line starts. There is no shortcut because the file is compressed. The encoding of a character depends on all the previous characters — the basic principle of gzip compression is to use shorter bit sequences for character sequences that have been encountered previously, and slightly longer bit sequences for character sequences that haven't been encountered yet, thus yielding a smaller file when character sequences are repeated. There's no way to determine that a particular character is a line break without examining all the previous characters. Your attempt, which decompresses the file, works on the decompressed stream, and recompresses to another file, is on the right track. You just need the correct command to truncate the file: tail -500 keeps the last 500 lines, which isn't what you want. Use head -n 499 to keep the first 499 lines, or head -n -1 to remove the last line. Not all systems support a negative argument for head ; if yours doesn't, you can use sed '$d' instead. gunzip <"$file" | head -n -1 | gzip >"$file".tmpmv -- "$file".tmp "$file" Note that you can't directly write to file: gunzip <"$file" | … | gzip >"$file" would start overwriting the file while gunzip is still reading it. The commands in a pipeline are executed in parallel. While it's possible to avoid creating a temporary file, it's a bad idea, because any way to do that would result in a truncated file if the command is interrupted, so I won't discuss how to do it. In theory, it would be possible to truncate a gzipped file by: uncompressing it in memory to determine the position where you want to truncate it; truncating the file to remove all data after the last character to keep; overwrite the last few bytes to correctly encode the last character; overwrite a few bytes at the beginning to reflect the new file size. However this can't be done with standard tools, it would take some custom programming, and it would leave an invalid file if it was interrupted.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/294710", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/172372/" ] }
294,720
I realized that cat sth and cat < sth both happen to give same output. Are they the same?
They're not completely identical. In cases where it matters, the redirection approach will generally give more annoying and obscure results (of course that might be what you want though). $ cat < /proc/self/maps$ cat /proc/self/maps55c61257e000-55c61258a000 r-xp 00000000 fd:00 1180143 /usr/bin/cat... Or try grep, the search program $ grep "grep" /proc/self/exeBinary file /proc/self/exe matches$ grep "grep" < /proc/self/exe$ Bit of a cheat, but you're most likely to run into this when using sudo , to run commands with root access: $ sudo cat < /etc/shadowbash: /etc/shadow: Permission denied$ sudo cat /etc/shadowroot:!::0:99999:7:::....
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/294720", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/178702/" ] }
294,742
I posted a question on ServerFault about a specialized Firewall setup , but as an avid software developer I am also considering rolling my own. I am only interested in using a high-level language, preferably Java or Node.JS. Is there some system for Linux or Illumos that will take all network packets, and provide them to my application to make a determination on whether they should be allowed, dropped or refused? (or re-written) I'm only interested in ICMP, UDP and TCP packets. I'm envisioning that I would write a Java application, that would allow me to sniff the traffic to make a determination on whether it should be allowed. For example, in HTTP traffic I may wish to check the Host header to determine what website the browser is attempting to visit. I realize this is likely to lower the potential throughput, but perhaps the solution you guys recommend will have documentation that will let me clarify the impact of that caveat. It's almost like I'm asking for FUSE, except for firewalls instead of filesystems. Is there such a program out there, or would I be stuck with writing C/C++ code for the firewall?
On Linux-based platforms there is a netlink socket that you can open from your Java program and determine whether or not to accept the packet. This socket can be included in the network stack with an iptables rule. Here of course you can also limit the types of packets to be passed to your usermode filter. Here's what the man page has to say on the matter: ULOG This target provides userspace logging of matching packets. When this target is set for a rule, the Linux kernel will multicast this packet through a netlink socket. One or more userspace processes may then subscribe to various multicast groups and receive the packets. Given the complexity and sophistication of the netfilter project, it might be worth asking for solutions to the problem you're trying to solve. (Or perhaps that's what your other SE question covered; I haven't looked yet )
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/294742", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/4910/" ] }
294,805
I have a problem with my Kali installation.Since I have updated it today, the mouse scrolling is inverted. I have tried the .Xmodmap method and also checking 'natural scroll' option but without success. Could anybody help me?
This seemed to be what i was looking for: How to *disable* natural scrolling? ... enter this at the command line: gsettings set org.gnome.desktop.peripherals.mouse natural-scroll false gsettings set org.gnome.desktop.peripherals.touchpad natural-scroll false
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/294805", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/178891/" ] }
294,835
Is there an easy way to substitute/evaluate environment variables in a file? Like let's say I have a file config.xml that contains: <property> <name>instanceId</name> <value>$INSTANCE_ID</value></property><property> <name>rootPath</name> <value>/services/$SERVICE_NAME</value></property> ...etc. I want to replace $INSTANCE_ID in the file with the value of the INSTANCE_ID environment variable, $SERVICE_NAME with the value of the SERVICE_NAME env var. I won't know a priori which environment vars are needed (or rather, I don't want to have to update the script if someone adds a new environment variable to the config file). Thanks!
You could use envsubst (part of gnu gettext ): envsubst < infile will replace the environment variables in your file with their corresponding value. The variable names must consist solely of alphanumeric or underscore ASCII characters, not start with a digit and be nonempty; otherwise such a variable reference is ignored. Some alternatives to gettext envsubst that support ${VAR:-default} and extra features: rust alternative go alternative node.js alternative To replace only certain environment variables, see this question.
{ "score": 8, "source": [ "https://unix.stackexchange.com/questions/294835", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/178917/" ] }
294,845
Running a brand new Ubuntu 16.04 and a Debian 8 server. Trying to connect via ssh and getting the following strange terminal output. I refer to the rectangles with the numbers in it. The problem with the language settings was introduced by myself trying to solve the just mentioned problem since I assumed some encoding problems to be responsible. After 3h of debugging I need your help! Maybe it's just a missing library? It is hard searching for such graphical problems... local@local:~$ ssh dummy@serverThe programs included with the Debian GNU/Linux system are free software;the exact distribution terms for each program are described in theindividual files in /usr/share/doc/*/copyright.Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extentpermitted by applicable law.Last login: Sat Jul 9 17:22:43 2016 from x590c3909.dyn.telefonica.de-bash: warning: setlocale: LC_ALL: cannot change locale (en_US.UTF-8)-bash: warning: setlocale: LC_ALL: cannot change locale (en_US.UTF-8)-bash: warning: setlocale: LC_ALL: cannot change locale (en_US.UTF-8)]1337;RemoteHost=dummy@server]1337;CurrentDir=/home/patrick]1337;ShellIntegrationVersion=2;shell=bash]133;C;]133;D;0]1337;RemoteHost=dummy@server]1337;CurrentDir=/home/patrick]133;Adummy@server:~$ ]133;B echo $PS1 output: echo $PS1]133;C;\[\e]0;\u@\h: \w\a\]${debian_chroot:+($debian_chroot)}\u@\h:\w\$ echo $TERM output: echo $TERM]133;C;xterm Edit: "locale" - warning fixed by this answer .
What your terminal is doing The "rectangles with the numbers in [them]" are the way that your terminal emulator is displaying a terminal control sequence to you, because it doesn't recognize that sequence. Specifically: There is an ECMA-48 control character (in the C1 group, for the technical) named Operating System Command , abbreviated OSC. It has the Unicode value U+009D. ECMA-48 defines a mechanism where characters in the C1 group, which require a fully clean 8-bit communications path in order to be transmitted, can be represented by an escape sequence that uses only characters with values less than U+0080 (128). These 7-bit aliases enable the use of C1 control characters on transmission paths that are not 8-bit clean. Ironically, the world has been largely 8-bit clean for decades, now. You'll most likely know one of these 7-bit aliases that is very common: ESC [ instead of the CSI control character (U+009B). The OSC control character has ESC ] as a 7-bit alias. Something on the far end of your SSH connection is expecting your terminal to understand control sequences that begin with OSC. It is transmitting them using the 7-bit alias. Your terminal doesn't fully implement ECMA-48. It's seeing ESC ] and just treating it as an ESC character followed by an ] character. And that's what it is printing. But it doesn't have a glyph for the ESC character. So it's falling back to the conventional trick of displaying characters that it doesn't have a glyph for as a box with the hexadecimal value of the (lowest 16 bits of the) Unicode code point in it. If you look closely, you'll see the numbers 00 and 1B in the box, for U+001B, the code point for the ESC character. It also doesn't correctly deal with the "spacing" of what it has printed for the ESC, i.e. the space that it takes on the screen, which is actually two character widths. So after printing the box it doesn't advance the output position enough . It then prints the ] over the top of the right-hand half of the box, as you can see. Why it has been told to do that Several terminal emulators recognize OSC as a control character sequence introducer. There's a standard form for it, even. ECMA-48 § 5.6 defines "control strings" begun with OSC and terminated with ST (U+009C, String Terminator ). What is in the control string is terminal-type specific. For example: You'll see from its doco that xterm implements such control strings, for setting fonts and window titles. However, the form of the control sequence in this case is not that of xterm. Rather, it is ␛]1337;CurrentDir=/home/patrick␇ This is the form for OSC control sequences that is understood by iTerm2. iTerm2 defines a set of control sequences introduced by OSC that are distinctly non-standard and idiosyncratic to iTerm2. They do not adhere to the ECMA-48 control string specification but terminate the control string with BEL (U+0007) rather than with ST as the standard says. Strictly speaking, that's a control string that isn't ever terminated , since any characters other than SOS and ST are permitted in the contents of a control string; and is one that with a conformant terminal emulator effectively just stops display, as the terminal simply accrues all further output as a control string. (The terminal emulator that is built in to the Linux kernel also doesn't implement standard OSC control strings. The xterm doco notes that it has bodges to support broken applications that use the non-conformant Linux kernel terminal emulator or iTerm2 forms. The form here is definitely iTerm2's, not that of the Linux kernel terminal emulator, though.) When you are using iTerm2 from your Macintosh, whatever is on the other end of the SSH connection is quietly sending iTerm2 control sequences to your terminal emulator to tell it stuff like what your shell is, what your working directory is, who you are, when you start editing at a shell prompt, when you start executing a command, and so forth. On the remote system, you have hardwired the terminal type . You've made it operate under the assumption that you're always talking to it with iTerm2. But you are now talking to it using Terminator running on Ubuntu, a different terminal emulator that has a different set of control sequences. In fact, the output even tells you this: ␛]1337;ShellIntegrationVersion=2;shell=bash␇ You've installed the iTerm2 "Shell Integration" for the Bourne Again shell on your remote system. Looking at it, it is pretty bad at checking that iTerm2 is actually the terminal that it is speaking to. So disable/uninstall it. Further reading Control Functions for Coded Character Sets . ECMA-48. ECMA International. console_codes . Linux manual pages. § 4. 2015. Matthew Freeman, George Nachman, and James A. Rosen. Proprietary Escape Codes . iTerm2 documentation. Matthew Freeman, George Nachman, and James A. Rosen. Shell Integration . iTerm2 documentation.
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/294845", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/135691/" ] }
294,864
lspci gives me the following information: $ lspci|grep VGA01:00.0 VGA compatible controller: NVIDIA Corporation GF104 [GeForce GTX 460] (rev a1) This is all correct, but this is generic name of the GPU. But Driver Manager — KDE Control Module — gives me much more interesting information: above all the options of drivers to install it says NVIDIA Corporation N460GTX Cyclone 1GD5/OC This is exactly the name the vendor (MSI) gave it. How can I find out such names without using KDE utilities? I'd prefer a console-based solution. In other words, where does the KCM take this name from?
You can use udevadm to get this information. For example on my system lspci gives me: # lspci|grep VGA 01:00.0 VGA compatible controller: NVIDIA Corporation GK106 [GeForce GTX 650 Ti Boost] (rev a1) Querying udev instead I get: # udevadm info -q property -p /sys/bus/pci/devices/0000:01:00.0 DEVPATH=/devices/pci0000:00/0000:00:02.0/0000:01:00.0DRIVER=nvidiaID_MODEL_FROM_DATABASE=GK106 [GeForce GTX 650 Ti Boost] (GeForce GTX 650 Ti Boost TwinFrozr II OC)ID_PCI_CLASS_FROM_DATABASE=Display controllerID_PCI_INTERFACE_FROM_DATABASE=VGA controllerID_PCI_SUBCLASS_FROM_DATABASE=VGA compatible controllerID_VENDOR_FROM_DATABASE=NVIDIA CorporationMODALIAS=pci:v000010DEd000011C2sv00001462sd00002874bc03sc00i00PCI_CLASS=30000PCI_ID=10DE:11C2PCI_SLOT_NAME=0000:01:00.0PCI_SUBSYS_ID=1462:2874SUBSYSTEM=pciUSEC_INITIALIZED=22791556 The ID_MODEL_FROM_DATABASE gives a more detailed description of the card. As for how to know the value to use for the -p argument, use the first part of the lspci output. For example if lspci showed 12:34.5 , you would use /sys/bus/pci/devices/0000:12:34.5
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/294864", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/27672/" ] }
294,888
I would like to write to a Device File (of a printer) located at /dev/usb/lp0 . The file is owned by lp user and group. This file is created whenever I connect my printer device to the system. I tried adding myself to the lp group. However the lp0 file doesn't appear when the printer is connected. Removing myself from the group fixes the issue. One solution to get write permission is to - Detect whenever the device is connected Trigger a shell script that runs sudo chmod 0666 /dev/usb/lp0 This led me to the answer at https://unix.stackexchange.com/a/28711 The shell script is successfully triggered but it doesn't run the sudo command *, since the shell script was not executed from the terminal. I have tried using sudo and gksudo , both have failed to prompt me to enter password i.e, I am unable to escalate permissions through a background shell script . What I have tried? setuid from Unix & Linux @ StackExchange , but it seems to be a very bad idea. echo 'my_insecure_password' | sudo -S command , it didn't work*. I did not try Polkit , which was suggested in other answers, due to the level of its complexity. But I am willing to go for it with proper directions.
Adding yourself to the lp group is probably the best solution here. That would not cause the lp0 file not to appear. (It's theoretically possible that your system has been configured to cause lp0 not to appear if you're in the lp group, but 1. that would have to be a local configuration, not a default setup from a distribution; and 2. I don't see why someone would have set this up.) What follows is for academic interest only. In your scenario, you don't need this. If you needed to change the permissions on the device file, then How to run custom scripts upon USB device plug-in? is not exactly what you need — that's for more complex cases that require a script. To change the Unix permissions or the ownership on a device file, use OWNER , GROUP and MODE assignments directly in the udev rule. That is, do create a file under /etc/udev/rules.d , but the line in that file should have something like GROUP="mygroup" instead of RUN="/path/to/script" . If you want to do something more complex, such as setting an access control list, you'll need to run a script. You don't need to escalate permissions in that script: it's already running as root! Just call the program you need to run as root, e.g. setfacl .
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/294888", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/178957/" ] }
294,908
I am playing with a script that, among other things, list a selection-list. As in: 1) Item 1 # (highlighted)2) Item 2 3) Item 3 # (selected)4) Item 4 When user press down-arrow next items is highlighted When user press up-arrow previous items is highlighted etc. When user press tab item is selected When user press shift+tab all items are selected / deselected When user press ctrl+a all items are selected ... This works fine as of current use, which is my personal use where input is filtered by my own setup. Question is how to make this reliable across various terminals. I use a somewhat hackish solution to read input: while read -rsn1 k # Read one key (first byte in key press)do case "$k" in [[:graph:]]) # Normal input handling ;; $'\x09') # TAB # Routine for selecting current item ;; $'\x7f') # Back-Space # Routine for back-space ;; $'\x01') # Ctrl+A # Routine for ctrl+a ;; ... $'\x1b') # ESC read -rsn1 k [ "$k" == "" ] && return # Esc-Key [ "$k" == "[" ] && read -rsn1 k [ "$k" == "O" ] && read -rsn1 k case "$k" in A) # Up # Routine for handling arrow-up-key ;; B) # Down # Routine for handling arrow-down-key ;; ... esac read -rsn4 -t .1 # Try to flush out other sequences ... esacdone And so on. As mentioned, question is how to make this reliable across various terminals: i.e. what byte sequences define a specific key. Is it even feasible in bash? One thought was to use either tput or infocmp and filter by the result given by that. I am however in a snag there as both tput and infocmp differ from what I actually read when actually pressing keys. Same goes for example using C over bash. for t in $(find /lib/terminfo -type f -printf "%f\n"); { printf "%s\n" "$t:"; infocmp -L1 $t | grep -E 'key_(left|right|up|down|home|end)';} Yield sequences read as defined for for example linux , but not xterm , which is what is set by TERM . E.g. arrow left: tput / infocmp : \x1 O D read : \x1 [ D What am I missing?
Adding yourself to the lp group is probably the best solution here. That would not cause the lp0 file not to appear. (It's theoretically possible that your system has been configured to cause lp0 not to appear if you're in the lp group, but 1. that would have to be a local configuration, not a default setup from a distribution; and 2. I don't see why someone would have set this up.) What follows is for academic interest only. In your scenario, you don't need this. If you needed to change the permissions on the device file, then How to run custom scripts upon USB device plug-in? is not exactly what you need — that's for more complex cases that require a script. To change the Unix permissions or the ownership on a device file, use OWNER , GROUP and MODE assignments directly in the udev rule. That is, do create a file under /etc/udev/rules.d , but the line in that file should have something like GROUP="mygroup" instead of RUN="/path/to/script" . If you want to do something more complex, such as setting an access control list, you'll need to run a script. You don't need to escalate permissions in that script: it's already running as root! Just call the program you need to run as root, e.g. setfacl .
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/294908", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/98945/" ] }
294,926
I've installed postgresql by pacman. Now I'm trying to run it: $ sudo systemctl start postgresql Job for postgresql.service failed because the control process exited with error code. See "systemctl status postgresql.service" and "journalctl -xe" for details. And then: $ sudo systemctl status postgresql ● postgresql.service - PostgreSQL database server Loaded: loaded (/usr/lib/systemd/system/postgresql.service; disabled; vendor preset: disabled) Active: failed (Result: exit-code) since Sun 2016-07-10 15:30:47 UTC; 17s ago Process: 19468 ExecStartPre=/usr/bin/postgresql-check-db-dir ${PGROOT}/data (code=exited, status=1/FAILURE) Jul 10 15:30:47 my_comp systemd[1]: Starting PostgreSQL database server... Jul 10 15:30:47 my_comp systemd[1]: postgresql.service: Control process exited, code=exited status=1 Jul 10 15:30:47 my_comp systemd[1]: Failed to start PostgreSQL database server. Jul 10 15:30:47 my_comp systemd[1]: postgresql.service: Unit entered failed state. Jul 10 15:30:47 my_comp systemd[1]: postgresql.service: Failed with result 'exit-code'. What's wrong with it?
Following step solved your problem step 1: create the data directory (acordingly with the PGROOT variable set before in the config file) sudo mkdir /var/lib/postgres/data Step 2: set /var/lib/postgres/data ownership to user 'postgres' chown postgres /var/lib/postgres/data Step 3: As user 'postgres' start the database. sudo -i -u postgresinitdb -D '/var/lib/postgres/data' Step 4: Start the service as root
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/294926", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/178905/" ] }
294,956
I installed tmux via apt-get and there is no .tmux.conf file in my home directory, even after I run tmux . I have been trying to follow a tmux tutorial, but the first part involves modifying this file, but since I do not have this file I am stuck. How do I get the tmux conf file?
There should be several example configuration files in either /usr/share/doc/tmux/examples or /usr/share/tmux/ . You can copy any of those over to ~/.tmux.conf to test out. Alternatively, you could create a ~/.tmux.conf with the default settings by using this command from within tmux: tmux show -g > ~/.tmux.conf This command works with tmux version 1.8. In older versions of tmux , a bug regarding redirecting stdout to a file might require this command: tmux show -g | cat > ~/.tmux.conf More info can be found here .
{ "score": 6, "source": [ "https://unix.stackexchange.com/questions/294956", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/47542/" ] }
294,964
I do have a interesting problem that I am trying to tackle but I amyet unable to do so. Let suppose that I have 2 arrays. Array One: 1 -2 3 -2 2 -4 Array Two: -2 -3 4 5 2 -5 I want to be able to actually compare the i-th value of both Array one and Array two : If both are negative then I would input in Array Three 0 If they are both positive I will add a 1 If they are opposites I need to insert a 2 Output: 2 0 1 2 1 0 How can I do that ?
If you're familiar with C, C++ or Java, then you'll find this variant of bash 's for -loop quite familiar too. bash does arithmetic evaluation with (( ... )) so we'll use that when comparing values: array1=( 1 -2 3 -2 2 -4 )array2=( -2 -3 4 5 2 -5 )array3=( )for (( i=0; i < ${#array1[@]}; ++i )); do if (( array1[i] < 0 && array2[i] < 0 )); then array3[$i]=0 elif (( array1[i] > 0 && array2[i] > 0 )); then array3[$i]=1 else array3[$i]=2 fidoneecho "${array3[@]}" This also works well with the ksh93 shell, from which bash got many of its features.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/294964", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/174662/" ] }
294,979
Condition: unable to troubleshoot failed installation of the library/module pywfdb from pip Differential conditions: failed dependenciens of pywfdb Exclude: upstart / systemd design bugs with runit in Ubuntu here since Ubuntu >=14.10 Settings PATH /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin PYTHONPATH blank in $HOME/.bashrc Work flow for dependencies and dirty installation with much logs Edwinksl's proposal: sudo apt-get install python-pyrex Reading package lists... DoneBuilding dependency treeReading state information... DoneThe following NEW packages will be installed:python-pyrex0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded. 2 not fully installed or removed.Need to get 181 kB of archives.After this operation, 996 kB of additional disk space will be used.Get:1 http://archive.ubuntu.com/ubuntu xenial/main amd64 python-pyrex all 0.9.8.5-2.1ubuntu1 [181 kB]Fetched 181 kB in 0s (356 kB/s) Selecting previously unselected package python-pyrex.(Reading database ... 434011 files and directories currently installed.)Preparing to unpack .../python-pyrex_0.9.8.5-2.1ubuntu1_all.deb ...Unpacking python-pyrex (0.9.8.5-2.1ubuntu1) ...Processing triggers for doc-base (0.10.7) ...Processing 1 added doc-base file...Registering documents with scrollkeeper...Processing triggers for man-db (2.7.5-1) ...Setting up runit (2.1.2-3ubuntu1) ...- -Setting up python-pyrex (0.9.8.5-2.1ubuntu1) ...- - Work flow with dirty installation to not clean up after the install, to see what pip was trying to do sudo -H pip install --no-clean pywfdb Collecting pywfdb Using cached pywfdb-0.1.1.zipBuilding wheels for collected packages: pywfdb Running setup.py bdist_wheel for pywfdb ... error Complete output from command /usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-_Tu9q1/pywfdb/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d /tmp/tmpemnpLdpip-wheel- --python-tag cp27: running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-2.7 creating build/lib.linux-x86_64-2.7/pywfdb copying pywfdb/__init__.py -> build/lib.linux-x86_64-2.7/pywfdb copying pywfdb/ecgcodes.py -> build/lib.linux-x86_64-2.7/pywfdb package init file 'example/__init__.py' not found (or not a regular file) creating build/lib.linux-x86_64-2.7/pywfdb/example copying example/readinfo.py -> build/lib.linux-x86_64-2.7/pywfdb/example copying example/plot.py -> build/lib.linux-x86_64-2.7/pywfdb/example running build_ext building 'pywfdb._pywfdb' extension creating build/temp.linux-x86_64-2.7 creating build/temp.linux-x86_64-2.7/pywfdb creating build/temp.linux-x86_64-2.7/wfdb-10.4.4 creating build/temp.linux-x86_64-2.7/wfdb-10.4.4/lib x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC -I./wfdb-10.4.4/lib -I/usr/include/python2.7 -c pywfdb/_pywfdb.c -o build/temp.linux-x86_64-2.7/pywfdb/_pywfdb.o -Wno-uninitialized -Wno-unused pywfdb/_pywfdb.c:15:22: fatal error: ecgcodes.h: No such file or directory #include "ecgcodes.h" ^ compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- Failed building wheel for pywfdb Running setup.py clean for pywfdb Failed to build pywfdb Installing collected packages: pywfdb Running setup.py install for pywfdb ... error Complete output from command /usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-_Tu9q1/pywfdb/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-gdKcwF-record/install-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build/lib.linux-x86_64-2.7 creating build/lib.linux-x86_64-2.7/pywfdb copying pywfdb/__init__.py -> build/lib.linux-x86_64-2.7/pywfdb copying pywfdb/ecgcodes.py -> build/lib.linux-x86_64-2.7/pywfdb package init file 'example/__init__.py' not found (or not a regular file) creating build/lib.linux-x86_64-2.7/pywfdb/example copying example/readinfo.py -> build/lib.linux-x86_64-2.7/pywfdb/example copying example/plot.py -> build/lib.linux-x86_64-2.7/pywfdb/example running build_ext building 'pywfdb._pywfdb' extension creating build/temp.linux-x86_64-2.7 creating build/temp.linux-x86_64-2.7/pywfdb creating build/temp.linux-x86_64-2.7/wfdb-10.4.4 creating build/temp.linux-x86_64-2.7/wfdb-10.4.4/lib x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC -I./wfdb-10.4.4/lib -I/usr/include/python2.7 -c pywfdb/_pywfdb.c -o build/temp.linux-x86_64-2.7/pywfdb/_pywfdb.o -Wno-uninitialized -Wno-unused pywfdb/_pywfdb.c:15:22: fatal error: ecgcodes.h: No such file or directory #include "ecgcodes.h" ^ compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-_Tu9q1/pywfdb/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-gdKcwF-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-_Tu9q1/pywfdb/ Open Why Failed building wheel for pywfdb ? Why the following error reproduced here from the full log? Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-_Tu9q1/pywfdb/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-gdKcwF-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-_Tu9q1/pywfdb/ Troubleshooting Methods Pip local modules where you see no wfdb found got by Adam's first command set " https://stackoverflow.com/a/23885252/54964 "['adium-theme-ubuntu==0.3.4', 'alabaster==0.7.8', 'auxlib==0.0.37', 'babel==2.3.4', 'backports-abc==0.4', 'backports.shutil-get-terminal-size==1.0.0', 'backports.ssl-match-hostname==3.5.0.1', 'beautifulsoup4==4.4.1', 'ccsm==0.9.12.2', 'certifi==2016.2.28', 'chardet==2.3.0', 'compizconfig-python==0.9.12.2', 'configparser==3.5.0', 'cycler==0.10.0', 'decorator==4.0.9', 'docutils==0.12', 'duplicity==0.7.6', 'entrypoints==0.2.2', 'enum34==1.1.6', 'functools32==3.2.3.post2', 'futures==3.0.5', 'html5lib==0.999', 'httplib2==0.9.1', 'imagesize==0.7.1', 'ipykernel==4.3.1', 'ipyparallel==5.0.1', 'ipython-genutils==0.1.0', 'ipython==4.2.0', 'ipywidgets==5.1.5', 'jinja2==2.8', 'jsonschema==2.5.1', 'jupyter-client==4.2.2', 'jupyter-core==4.1.0', 'lockfile==0.12.2', 'lxml==3.5.0', 'markupsafe==0.23', 'matlab-kernel==0.9.6', 'matplotlib==1.5.1', 'metakernel==0.13.0', 'mistune==0.7.2', 'nbconvert==4.2.0', 'nbformat==4.0.1', 'nose==1.3.7', 'notebook==4.2.1', 'numpy==1.11.0', 'pandas==0.18.1', 'path.py==8.2.1', 'pathlib2==2.1.0', 'pdfshuffler==0.6.0', 'pexpect==4.1.0', 'pickleshare==0.7.2', 'pillow==3.1.2', 'pip==8.1.2', 'ptyprocess==0.5.1', 'pycosat==0.6.1', 'pycurl==7.43.0', 'pygments==2.1.3', 'pygobject==3.20.0', 'pyicu==1.9.2', 'pymatbridge==0.5.2', 'pymysql==0.7.2', 'pyparsing==2.1.4', 'pypdf==1.13', 'python-dateutil==2.5.3', 'python-djvulibre==0.7', 'pytz==2016.4', 'pyxdg==0.25', 'pyyaml==3.11', 'pyzmq==15.2.0', 'qtconsole==4.2.1', 'requests==2.10.0', 'scour==0.32', 'setuptools==22.0.5', 'simplegeneric==0.8.1', 'singledispatch==3.4.0.3', 'six==1.10.0', 'snowballstemmer==1.2.1', 'sphinx==1.4.3', 'subprocess32==3.2.6', 'terminado==0.6', 'testpath==0.3', 'tornado==4.3', 'traitlets==4.2.1', 'unity-lens-photos==1.0', 'wheel==0.29.0', 'widgetsnbextension==1.2.3'] Unsuccessful test commands for the info of the package/module/library pip search wfdb gives pywfdb (0.1.1) - Python interface to WFDB library so I expect it to include also the module which you can import . find /usr/local/lib/python2.7/dist-packages -name '*wfdb*' returns blank. pip list |grep wfdb returns blank. pip show pywfdb returns blank. Test code which shows that the module is not found " http://www.pybytes.com/pywfdb/ "import pywfdb Trying to search the module Not installed as normal python package because not in /usr/lib/python<version>/site-packages as described here ; I searched all directories ( /usr/local/lib/python2.7/ and /usr/local/lib/python3.5/ ). Not in dist-packages based on the answer . Command ls /usr/local/lib/python2.7/dist-packages/ | grep wfdb returns blank. >>> import site; site.getsitepackages() gives the output ['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages'] Blank outputs for ls /usr/local/lib/python2.7/dist-packages | grep wfdb and ls /usr/lib/python2.7/dist-packages | grep wfdb . System: Linux Ubuntu 16.04 64 bit Linux kernel: 4.6 Linux kernel options: wl Hardware: Macbook Air 2013-mid Python: 2.7.11+ Pip: latest (8.1.2) pip install --upgrade pip returns Requirement already up-to-date: pip in /home/masi/.local/lib/python2.7/site-packages Latest pip modules : pip freeze --local | grep -v '^\-e' | cut -d = -f 1 | xargs -n1 pip install -U done before Bash: 4.3.46(1)-release (x86_64-pc-linux-gnu)
If you're familiar with C, C++ or Java, then you'll find this variant of bash 's for -loop quite familiar too. bash does arithmetic evaluation with (( ... )) so we'll use that when comparing values: array1=( 1 -2 3 -2 2 -4 )array2=( -2 -3 4 5 2 -5 )array3=( )for (( i=0; i < ${#array1[@]}; ++i )); do if (( array1[i] < 0 && array2[i] < 0 )); then array3[$i]=0 elif (( array1[i] > 0 && array2[i] > 0 )); then array3[$i]=1 else array3[$i]=2 fidoneecho "${array3[@]}" This also works well with the ksh93 shell, from which bash got many of its features.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/294979", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/16920/" ] }
294,984
I'm writing a Perl script that parses logfiles to collect PIDs and then checks whether that PID is running. I am trying to think of the best way to make that check. Obviously, I could do something like: system("ps $pid > /dev/null") && print "Not running\n"; However, I'd prefer to avoid the system call if possible. I therefore thought I could use the /proc filesystem (portability isn't a concern, this will always be running on a Linux system). For example: if(! -d "/proc/$pid"){ print "Not running\n";} Is that safe? Can I always asume that if there's no /proc/$pid/ directory the associated PID is not running? I expect so since AFAIK ps itself gets its information from /proc anyway but since this is for production code, I want to be sure. So, can there be cases where a running process has no /proc/PID directory or where a /proc/PID directory exists and the process is not running? Is there any reason to prefer parsing ps over checking for the existence of the directory?
The perl function kill(0,$pid) can be used. If the return code is 1 then the PID exists and you're allowed to send a signal to it. If the return code is 0 then you need to check $!. It may be EPERM (permission denied) which means the process exists or ESRCH in which case the process doesn't exist. If your checking code is running as root then you can simplify this to just checking the return code of kill; 0=>error, 1=>ok For example: % perl -d -e 0Loading DB routines from perl5db.pl version 1.37Editor support available.Enter h or 'h h' for help, or 'man perldebug' for more help.main::(-e:1): 0 DB<1> print kill(0,500)0 DB<2> print $!No such process DB<3> print kill(0,1)0 DB<4> print $!Operation not permitted DB<5> print kill(0,$$)1 This can be made into a simple function use Errno;sub test_pid($){ my ($pid)=@_; my $not_present=(!kill(0,$pid) && $! == Errno::ESRCH); return($not_present);}print "PID 500 not present\n" if test_pid(500);print "PID 1 not present\n" if test_pid(1);print "PID $$ not present\n" if test_pid($$);
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/294984", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/22222/" ] }
295,005
On my system (Darwin 15.5.0), man(1) opens as follows: NAME man - format and display the on-line manual pages The file the page is formatted from, however, is clearly on disk: % man -w man/usr/share/man/man1/man.1% file `man -w man`/usr/share/man/man1/man.1: troff or preprocessor input text So, "on-line" in this case does not mean "online," as in, "somewhere else accessible over the Internet." Does "on-line" just mean that my system is powered on? If so, why bother specifying that in the first place, i.e., isn't it obvious that I'm reading a page that the formatter processed? Or, when the description was written, was it a huge deal to have a manual on disk because most "manuals" then were paper volumes? Is this usage of "on-line," hyphen and all, still common in computing?
In contrast to a printed (hard-copy) manual, which you could read off-line (while not using a computer). The term dates back (at least) to time-sharing systems. Users may have had a terminal which could be used for typing text, punching paper tapes. But they were only able to use the computer when they were on-line (the "line" referring to the communications link from the terminal to the computer). Lots of English is that way: you likely use terms which on reflection you might not consider up-to-date.
{ "score": 6, "source": [ "https://unix.stackexchange.com/questions/295005", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/179054/" ] }
295,017
I run Xvfb with command: Xvfb :1 -screen 0 100x100x16 -fbdir /tmp And it's working fine. I can connect via VNC, and now under /tmp directory I have Xvfb_screen0 binary file. I thought it will act like /dev/fb0 so I tried to change its settings with fbset like: sudo fbset -fb /tmp/Xvfb_screen0 -xres 500 -yres 500 But the command finishes with error: ioctl FBIOGET_VSCREENINFO: Inappropriate ioctl for device Is there any way to change running Xvfb server resolution?
In contrast to a printed (hard-copy) manual, which you could read off-line (while not using a computer). The term dates back (at least) to time-sharing systems. Users may have had a terminal which could be used for typing text, punching paper tapes. But they were only able to use the computer when they were on-line (the "line" referring to the communications link from the terminal to the computer). Lots of English is that way: you likely use terms which on reflection you might not consider up-to-date.
{ "score": 6, "source": [ "https://unix.stackexchange.com/questions/295017", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/179033/" ] }
295,022
I have a number of functions defined in my .bashrc , intented to be used interactively in a terminal. I generally preceded them with a comment describing its intended usage: # Usage: foo [bar]# Foo's a bar into a bazfoo() { ...} This is fine if browsing the source code, but it's nice to run type in the terminal to get a quick reminder of what the function does. However this (understandably) doesn't include comments: $ type foofoo is a functionfoo (){ ...} Which got me thinking "wouldn't it be nice if these sort of comments persisted so that type could display them?" And in the spirit of Python's docstrings I came up with this: foo() { : Usage: foo [bar] : "Foo's a bar into a baz" ...}$ type foofoo is a functionfoo (){ : Usage: foo [bar]; : "Foo's a bar into a baz"; ...} Now the usage is included right in the type output! Of course as you can see quoting becomes an issue which could be error-prone, but it's a nicer user experience when it works. So my question is, is this a terrible idea? Are there better alternatives (like a man / info for functions) for providing users of Bash functions with additional context? Ideally I'd still like the usage instructions to be located nearby the function definition so that people viewing the source code also get the benefit, but if there's a "proper" way to do this I'm open to alternatives. Edit these are all fairly simple helper-style functions and I'm just looking to get a little extra context interactively. Certainly for more complex scripts that parse flags I'd add a --help option, but for these it would be somewhat burdensome to add help flags to everything. Perhaps that's just a cost I should accept, but this : hack seems to work reasonably well without making the source much harder to read our edit.
I don't think that there is just one good way to do this. Many functions, scripts, and other executables provide a help message if the user provides -h or --help as an option: $ foo() {[[ "$1" =~ (-h|--help) ]] && { cat <<EOFUsage: foo [bar]Foo's a bar into a bazEOFreturn;}: ...other stuff...} For example: $ foo -hUsage: foo [bar]Foo's a bar into a baz$ foo --helpUsage: foo [bar]Foo's a bar into a baz
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/295022", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/19157/" ] }
295,033
I would like to convert this Bash loop: x="one two three"for i in ${x}do echo ${i}done in such a way to work with both Bash and zsh This solution works: x=( one two three )for i in ${x[@]}do echo ${i}done Anyway I am modifying x from a string to an array. Is there a way to loop over $x in zsh when it is a string and in a way compatible with Bash? I know about zsh setopt shwordsplit to emulate Bash, but I can't set it ad hoc for the loop, because it would not work in Bash. `
if type emulate >/dev/null 2>/dev/null; then emulate ksh; fi In zsh, this activates options that make it more compatible with ksh and bash, including sh_word_split . In other shells, emulate doesn't exist so this does nothing.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/295033", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/44919/" ] }
295,045
I am trying to recursively change file permissions in a wordpress installation affecting everything below the public_html document root folder, excluding certain folders. I have set extglob on with shopt -s extglob When I run the following command it fails to exclude the folder I want it to exclude ls -R -alh ./public_html/!(*uploads*) | grep uploads The above lists numerous files in the uploads folder -- it should not list any. Of course the command above is only a test; I'll be using chmod in the actual script. I have tried numerous different combinations and all have failed; for example, the following: ls -R -alh ./public_html/!(wp-content/uploads*) ls: cannot access ./public_html/!(wp-content/uploads*): No such file or directory This is my first attempt to use exclusions with shell commands and I might be making a simple mistake. Any ideas what I am doing wrong? Please note: the purpose of the question is to better understand extglob rather than find alternatives. I can script alternatives but as I have never used extglob before I am having trouble understanding the syntax.
First, the extglob controls what ls sees on its command line. It does not control what ls does with what it sees on the command line. This is important because the -R option to ls tells ls to explore recursively any directories it sees on the command line. So, even if the *uploads* directories are not given explicitly on the command line, ls will find them when it explores their parent directories. Second, as you know, don't parse ls . The output of ls is not meant for use in pipelines or scripts. Trying to use it that way eventually leads to unhappiness. Third, to get the files that you want, try: find ./public_html ! -path '*uploads*' To explain: The ./public_html tells find to start looking in the ./public_html directory. By itself, the option -path '*uploads*' matches on any path that contains the pattern *uploads* . ( -path is similar to find's -name option but path includes the directory names.) The preceding ! , however, indicates negation. So, the option ! -path '*uploads*' excludes any path matching *uploads* . To get ls style output while still using the features of find , consider: find ./public_html ! -path '*uploads*' -exec ls -dalh {} +
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/295045", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/3568/" ] }
295,060
I've seen on various Linux systems where instead of the real device node (for example: /dev/sda1 ), the root device appears as /dev/root , or instead of the real filesystem, mtab says it is a filesystem called rootfs (which appears as a real filesystem in /proc/filesystems , but doesn't have code in <linux-kernel-source-tree>/fs ). Various utilities have been made to use certain attributes to determine the real root device node (such as rdev, and the Chromium OS rootdev). I can find no logical explanation to this other than reading somewhere that very-small embedded devices don't always have to have a /dev device node for their root device. (Is this true, and if so, is that the answer to my question?) Why does mtab sometimes say /dev/root (and I think I might have seen it say rootdev once) instead of the real device node, and how can I make it always say the real device node? The kernel first mounts the root device following the root parameter in the cmdline, then init/systemd re-mounts it according to the fstab , correct? If so, then I presume init maintains mtab . If my theory is correct, how can I make init write the real root device node to mtab ? I noticed that /etc/mtab is actually a symbolic link to /proc/mounts , which would mean mtab is maintained by the kernel. So how do I configure/patch a kernel to, instead of saying the root devices node path is /dev/root , have mtab contain the real device node?
This is generally an artifact of using an initramfs. From the kernel documentation ( https://www.kernel.org/doc/Documentation/filesystems/ramfs-rootfs-initramfs.txt ) What is rootfs? Rootfs is a special instance of ramfs (or tmpfs, if that's enabled), which is always present in 2.6 systems. You can't unmount rootfs for approximately the same reason you can't kill the init process; rather than having special code to check for and handle an empty list, it's smaller and simpler for the kernel to just make sure certain lists can't become empty. Most systems just mount another filesystem over rootfs and ignore it. The amount of space an empty instance of ramfs takes up is tiny. Thus rootfs is the root filesystem that was created for the initramfs, and can't be unmounted. In regards to /dev/root , I'm less certain on this, but if I recall correctly /dev/root is created when using an initrd (not the same as an initramfs).
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/295060", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/153468/" ] }
295,061
I have two files, file1 and file2 . The sample content of file1 is: A BC DE FG H and the content of file2 is like: A Bfew other linesE Ffew more other linesA BC DE FG Hfew more other linesG H So I want to search the whole block of file1 content in file2 only.This means the output should contain only these lines: A BC DE FG H please note that :- only the lines which are coming together , should be the part of output.
grep is pretty stupid when it comes to multiline patterns, but translating all newline characters \n of both the pattern and the text to search into NUL characters \0 before comparing them fixes this. Translating \0 in the output back to \n is obviously also needed. Here's your command, assuming that file1 contains the pattern you want to search in file2 : grep -aof <(tr '\n' '\0' < file1) <(tr '\n' '\0' < file2) | tr '\0' '\n' Example output for your given files: A BC DE FG H Explanation: <(tr '\n' '\0' < file1) creates a FIFO/named pipe/temporary file-like object that equals file1 , but with all newline characters translated to NUL characters. <(tr '\n' '\0' < file2) does the same, but for file2 . grep -f PATTERN_FILE INPUT_FILE searches for the pattern(s) from PATTERN_FILE in INPUT_FILE . The -a flag of grep enables matching on binary files. This is needed because otherwise it would skip files that contain non-printable characters like \0 . The -o flag of grep makes it print only the matching sequence, not the whole line where it has been found. | tr '\0' '\n' translates all NUL characters from the output of the command on the left side back to newline characters.
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/295061", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/177093/" ] }
295,090
I have a bash script which copies data across to a USB stick. It works. The data is copied across fine, but the filenames are always changed. They are the same as they were before, but any longer names are cut to only 8 chars long, and have an extension that is only 3 chars long (11 char max total). So an original file called "willGetCutShorter.html" becomes "willGetS.htm" on the drive, whereas "small.txt" stays the same. Copied directory names are cut in the same way, all appearing 8 chars long (they have no extension, of course). I don't want this to happen. I want the file and directory names to not be modified at all. I don't know why this is happening either. In my bash script, I copy everything in my computer directory to the drive using an asterisk to represent all the computer directory contents. I'm wondering if this is why? Perhaps cp is only grabbing part of the filename? Also, while in Linux the files appear all in lowercase, even stuff that was originally part uppercase. In Windows however, all files and folders are uppercase. Why? EDIT #1 I formatted the USB drive on a Windows 7 machine before I started using it in this way. In my /etc/fstab file I have added an entry for the drive that mounts it as msdos. This was because I read a manual page (probably 'man mount') and it said that the drive format, which is FAT32, is covered by msdos. I wanted to mount it with FAT32 as the filesystem type, but I couldn't see that option in the mount manual page. The fstab entry means the mount command consists of only this: sudo mount /mnt/ The copy commands in the bash script are all like this: cp -f -r /path/to/dir/* /mnt/to/dir/ It sounds like I just need to reformat the drive to something else, or mount it slightly differently?
I suspect you are using a mount command like the one below: mount -t msdos /dev/XYZ /mnt/test This will force the partition to be mounted in legacy DOS FAT filesystem which uses the 8.3 filename convention (See https://en.wikipedia.org/wiki/8.3_filename ) instead of vfat which uses Long filenames ( https://en.wikipedia.org/wiki/Long_filename ). Recommend using either of the below options for mount: mount /dev/XYZ /mnt/test (by default uses vfat, if it is FATXX formatted USB stick) or mount -t vfat /dev/XYZ /mnt/test (explicitly mount as vfat, if it is FATXX formatted USB stick)
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/295090", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/-1/" ] }
295,122
I'm trying to install some packages with apt-get but it seems to be stuck in some sort of dependency loop. I have read similar questions/answers but none of the solutions given work. This is the output and error messages of apt-get install -f . It looks like a problem with python? Any advice? Many thanks. sudo apt-get install -fReading package lists... DoneBuilding dependency treeReading state information... DoneCorrecting dependencies... DoneThe following packages were automatically installed and are no longer required: cdbs freepats gir1.2-gtksource-3.0 gir1.2-gucharmap-2.90 glib-networking-common gnustep-common gsettings-desktop-schemas gstreamer0.10-plugins-bad gstreamer0.10-x html2text libaa1 libao-common libao4 libass4 libaudio2 libavc1394-0 libblas-dev libbz2-dev libcaca0 libcdaudio1 libdc1394-22 libdca0 libdirectfb-1.2-9 libdv4 libdvdnav4 libdvdread4 libenca0 libfaad2 libflite1 libgail-3-0 libgeoclue0 libgme0 libgraphite3 libgstreamer-plugins-bad0.10-0 libgucharmap-2-90-7 libiec61883-0 libjpeg8-dev libkate1 libkpathsea6 liblapack-dev liblcms1 libmhash2 libmimic0 libmms0 libmodplug1 libmpcdec6 libnotify4 libobjc4 libofa0 libopenal-data libopenal1 libopus0 libpoppler19 libptexenc1 libraptor2-0 librasqal3 libraw1394-11 librdf0 libreadline-dev libshout3 libslv2-9 libsoundtouch0 libspandsp2 libtag1-vanilla libtag1c2a libts-0.0-0 libvo-aacenc0 libvo-amrwbenc0 libwavpack1 libwebkitgtk-3.0-common libwildmidi-config libwildmidi1 libxfont1 libyajl2 libyaml-tiny-perl libzbar0 libzvbi-common libzvbi0 lmodern luatex notification-daemon tex-common tex-gyre texlive-common texlive-doc-base texlive-fonts-recommended-doc texlive-latex-base-doc texlive-latex-recommended-doc texlive-pstricks-doc tsconf ttf-dejavu ttf-freefont ttf-marvosym xfonts-encodings xfonts-utils yelp-xsl zenity-commonUse 'apt-get autoremove' to remove them.The following extra packages will be installed: aspell build-essential dictionaries-common dpkg-dev gir1.2-freedesktop gir1.2-glib-2.0 gobject-introspection ienglish-common ispell libalgorithm-diff-xs-perl libapt-pkg-perl libaspell15 libaugeas0 libauthen-pam-perl libbit-vector-perl libbsd-resource-perl libcairo-perl libclass-c3-xs-perl libclass-methodmaker-perl libclone-perl libconfig-augeas-perl libconvert-binary-c-perl libcrypt-ssleay-perl libcurses-perl libdata-alias-perl libdate-calc-xs-perl libdbd-mysql-perl libdbd-pg-perl libdbd-sqlite3-perl libdbi-perl libdpkg-perl libelfg0 libfcgi-perl libfile-fcntllock-perl libfuse-perl libgd-perl libgirepository-1.0-1 libgirepository1.0-dev libglib-perl libglib2.0-0 libglib2.0-bin libglib2.0-dev libio-pty-perl liblocale-gettext-perl libtext-iconv-perl patch perl-base python python-gi python-gi-cairoSuggested packages: aspell-doc spellutils debian-keyring spell augeas-tools libfont-freetype-perl libmldbm-perl libnet-daemon-perl libsql-statement-perl libunix-mknod-perl liblchown-perl libfilesys-statvfs-perl libgirepository1.0-doc diffutils-doc python-doc python-tkRecommended packages: iamerican iamerican-small iamerican-large iamerican-huge iamerican-insane ibritish ibritish-small ibritish-large ibritish-huge ibritish-insane xdg-user-dirsThe following packages will be REMOVED: libgd-gd2-perlThe following NEW packages will be installed: aspell build-essential dictionaries-common dpkg-dev ienglish-common ispell libdpkg-perl libelfg0 libgd-perl libio-pty-perl libtext-iconv-perlThe following packages will be upgraded: gir1.2-freedesktop gir1.2-glib-2.0 gobject-introspection libalgorithm-diff-xs-perl libapt-pkg-perl libaspell15 libaugeas0 libauthen-pam-perl libbit-vector-perl libbsd-resource-perl libcairo-perl libclass-c3-xs-perl libclass-methodmaker-perl libclone-perl libconfig-augeas-perl libconvert-binary-c-perl libcrypt-ssleay-perl libcurses-perl libdata-alias-perl libdate-calc-xs-perl libdbd-mysql-perl libdbd-pg-perl libdbd-sqlite3-perl libdbi-perl libfcgi-perl libfile-fcntllock-perl libfuse-perl libgirepository-1.0-1 libgirepository1.0-dev libglib-perl libglib2.0-0 libglib2.0-bin libglib2.0-dev liblocale-gettext-perl patch perl-base python python-gi python-gi-cairo39 upgraded, 11 newly installed, 1 to remove and 1067 not upgraded.14 not fully installed or removed.Need to get 0 B/17.7 MB of archives.After this operation, 11.2 MB of additional disk space will be used.Do you want to continue [Y/n]?Reading changelogs... DoneExtracting templates from packages: 100%Preconfiguring packages ... dict-common::dc_set: dictionaries-common/default-ispell is already set to [american (American English)]. Preserving it. dict-common::dc_set: dictionaries-common/default-wordlist is already set to [american (American English)]. Preserving it.Setting up python-minimal (2.7.9-1) ...Traceback (most recent call last): File "/usr/local/lib/python2.7/runpy.py", line 162, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/usr/local/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/usr/local/lib/python2.7/compileall.py", line 16, in <module> import struct File "/usr/local/lib/python2.7/struct.py", line 1, in <module> from _struct import *ImportError: No module named _structdpkg: error processing package python-minimal (--configure): subprocess installed post-installation script returned error exit status 1Errors were encountered while processing: python-minimalE: Sub-process /usr/bin/dpkg returned an error code (1) EDIT: As suggested I have tried to use apt-get to reinstall python-minimal and get the following errors sudo apt-get install --reinstall python2.7-minimalReading package lists... DoneBuilding dependency treeReading state information... DoneYou might want to run 'apt-get -f install' to correct these:The following packages have unmet dependencies: libalgorithm-diff-xs-perl : Depends: perlapi-5.14.2 libapt-pkg-perl : Depends: perlapi-5.14.2 libbit-vector-perl : Depends: perlapi-5.14.2 libbsd-resource-perl : Depends: perlapi-5.14.2 libcairo-perl : Depends: perlapi-5.14.2 libclass-c3-xs-perl : Depends: perlapi-5.14.2 libclass-methodmaker-perl : Depends: perlapi-5.14.2 libclone-perl : Depends: perlapi-5.14.2 libconfig-augeas-perl : Depends: perlapi-5.14.2 libconvert-binary-c-perl : Depends: perlapi-5.14.2 libcrypt-ssleay-perl : Depends: perlapi-5.14.2 libcurses-perl : Depends: perlapi-5.14.2 libdata-alias-perl : Depends: perlapi-5.14.2 libdate-calc-xs-perl : Depends: perlapi-5.14.2 libdbd-mysql-perl : Depends: perlapi-5.14.2 libdbd-pg-perl : Depends: perlapi-5.14.2 libdbd-sqlite3-perl : Depends: perlapi-5.14.2 libdbi-perl : Depends: perlapi-5.14.2 libfcgi-perl : Depends: perlapi-5.14.2 libfile-fcntllock-perl : Depends: perlapi-5.14.2 libfuse-perl : Depends: perlapi-5.14.2 libgd-gd2-perl : Depends: perlapi-5.14.2 libglib-perl : Depends: perlapi-5.14.2 liblocale-gettext-perl : PreDepends: perlapi-5.14.2 python : Depends: python-minimal (= 2.7.3-4+deb7u1) but 2.7.9-1 is to be installed python-dev : Depends: python (= 2.7.9-1) but 2.7.3-4+deb7u1 is to be installedE: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).sudo apt-get upgradeReading package lists... DoneBuilding dependency treeReading state information... DoneYou might want to run 'apt-get -f install' to correct these.The following packages have unmet dependencies: aspell-en : Depends: aspell (>= 0.60.3-2) but it is not installed Depends: dictionaries-common (>= 0.49.2) but it is not installed iamerican : Depends: dictionaries-common but it is not installed Depends: ienglish-common (= 3.3.02-6) but it is not installed Depends: ispell but it is not installed ibritish : Depends: dictionaries-common but it is not installed Depends: ienglish-common (= 3.3.02-6) but it is not installed Depends: ispell but it is not installed libalgorithm-diff-xs-perl : Depends: perlapi-5.14.2 libapt-pkg-perl : Depends: perlapi-5.14.2 libbit-vector-perl : Depends: perlapi-5.14.2 libbsd-resource-perl : Depends: perlapi-5.14.2 libcairo-perl : Depends: perlapi-5.14.2 libclass-c3-xs-perl : Depends: perlapi-5.14.2 libclass-methodmaker-perl : Depends: perlapi-5.14.2 libclone-perl : Depends: perlapi-5.14.2 libconfig-augeas-perl : Depends: perlapi-5.14.2 libconvert-binary-c-perl : Depends: perlapi-5.14.2 libcrypt-ssleay-perl : Depends: perlapi-5.14.2 libcurses-perl : Depends: perlapi-5.14.2 libdata-alias-perl : Depends: perlapi-5.14.2 libdate-calc-xs-perl : Depends: perlapi-5.14.2 libdbd-mysql-perl : Depends: perlapi-5.14.2 libdbd-pg-perl : Depends: perlapi-5.14.2 libdbd-sqlite3-perl : Depends: perlapi-5.14.2 libdbi-perl : Depends: perlapi-5.14.2 libfcgi-perl : Depends: perlapi-5.14.2 libfile-fcntllock-perl : Depends: perlapi-5.14.2 libfuse-perl : Depends: perlapi-5.14.2 libgd-gd2-perl : Depends: perlapi-5.14.2 libglib-perl : Depends: perlapi-5.14.2 liblocale-gettext-perl : PreDepends: perlapi-5.14.2 python : Depends: python-minimal (= 2.7.3-4+deb7u1) but 2.7.9-1 is installed python-dev : Depends: python (= 2.7.9-1) but 2.7.3-4+deb7u1 is installedE: Unmet dependencies. Try using -f.
I suspect you are using a mount command like the one below: mount -t msdos /dev/XYZ /mnt/test This will force the partition to be mounted in legacy DOS FAT filesystem which uses the 8.3 filename convention (See https://en.wikipedia.org/wiki/8.3_filename ) instead of vfat which uses Long filenames ( https://en.wikipedia.org/wiki/Long_filename ). Recommend using either of the below options for mount: mount /dev/XYZ /mnt/test (by default uses vfat, if it is FATXX formatted USB stick) or mount -t vfat /dev/XYZ /mnt/test (explicitly mount as vfat, if it is FATXX formatted USB stick)
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/295122", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/179144/" ] }
295,125
I have bunch of log files which I am trying to encrypt with public/private key using openssl and save to my NAS but it is failing. My log files are in the following path : /var/SYSLOGS/hosts/archive My public key and private key are in /etc/log-enc/ [root@NAG01 log-enc]# ls -ltotal 8-rw-r--r-- 1 root root 891 Jul 11 15:58 syslog_privalye_key.pem-rw-r--r-- 1 root root 272 Jul 11 15:59 syslog_public_key.pem Now I am trying to execute following commandIf I am executing the same command one by one, then there is no issue. for file in `find /var/SYSLOGS/hosts/archive/`do FILE_BASE=$(basename $file)echo "$file=>/NFS/Nag01/syslogs/hosts/$FILE_BASE.enc"openssl rsautl -encrypt -inkey /etc/log-enc/syslog_public_key.pem -pubin -in $file -out /NFS/Nag01/syslogs/hosts/$FILE_BASE.encdone Here are the error logs RSA operation error140628568049480:error:0406D06E:rsa routines:RSA_padding_add_PKCS1_type_2:data too large for key size:rsa_pk1.c:151:/var/SYSLOGS/hosts/archive/192.168.33.5.log-20160131.gz=>/NFS/Nag01/syslogs/hosts/192.168.33.5.log-20160131.gz.encRSA operation error140123978278728:error:0406D06E:rsa routines:RSA_padding_add_PKCS1_type_2:data too large for key size:rsa_pk1.c:151:/var/SYSLOGS/hosts/archive/app02.log-20160306.gz=>/NFS/Nag01/syslogs/hosts/app02.log-20160306.gz.enc/var/SYSLOGS/hosts/archive/192.168.34.8.log-20160227.gz=>/NFS/Nag01/syslogs/hosts/192.168.34.8.log-20160227.gz.encRSA operation error139777258493768:error:0406D06E:rsa routines:RSA_padding_add_PKCS1_type_2:data too large for key size:rsa_pk1.c:151:/var/SYSLOGS/hosts/archive/192.168.31.3.log-20160511.gz=>/NFS/Nag01/syslogs/hosts/192.168.31.3.log-20160511.gz.enc Here are the raw files. [root@NAG01 log-enc]# ls -l /var/SYSLOGS/hosts/archive/192.168.33.5.log-20160131.gz-rw-------. 1 root root 3569 Jan 31 04:16 /var/SYSLOGS/hosts/archive/192.168.33.5.log-20160131.gz[root@NAG01 log-enc]# ls -l /var/SYSLOGS/hosts/archive/192.168.34.8.log-20160227.gz-rw-------. 1 root root 2142 Feb 27 03:11 /var/SYSLOGS/hosts/archive/192.168.34.8.log-20160227.gz
I suspect you are using a mount command like the one below: mount -t msdos /dev/XYZ /mnt/test This will force the partition to be mounted in legacy DOS FAT filesystem which uses the 8.3 filename convention (See https://en.wikipedia.org/wiki/8.3_filename ) instead of vfat which uses Long filenames ( https://en.wikipedia.org/wiki/Long_filename ). Recommend using either of the below options for mount: mount /dev/XYZ /mnt/test (by default uses vfat, if it is FATXX formatted USB stick) or mount -t vfat /dev/XYZ /mnt/test (explicitly mount as vfat, if it is FATXX formatted USB stick)
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/295125", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/72048/" ] }
295,131
I am very much new to Embedded Linux. We use poky build system. We just use bitbake linux-imx command to build the kernel. It generates some files zImage, rootfs, uboot and also a sdcard image. We just copy the sdcard image and run the linux on our custom board. My questions what does rootfs and zImage actually contain??
To understand what every file is responsible for you should understand how MPU starts up. As I understood from your qestion you use NXP (Freescale) i.MX microprocessor family. It includes small ROM loader, which will make basic system setup (interfaces to memory, clock tree etc.), search for media to boot from (based on burned OTP bits or GPIO), find bootloader (u-boot in your case) in exact address which is specified in datasheet, load and start it. U-boot will init more interfaces (e.g. Ethernet), find arguments that should be passed to Kernel (screen settings, console, network settings if you use NFS), copy Kernel to DDR and pass all arguments. Kernel will load all drivers, and search for rootfs with all libraries, applications etc. After this Kernel will start init scripts, which will init all system and start your application. u-boot is the first thing that will start after ROM bootloader.You can replace it with your own code if you would like MPU to runbare-metal code without OS (like microcontroller). zImage is compressed version of the Linux kernel image that isself-extracting. rootfs is root file system, which contains allapplications, libs and in most cases everything, including homefolder. sdcard image is just all stuff mentioned above which canbe copied (with dd) to the card, after copy you will see FATpartition with Kernel and device tree and EXT partition with rootfs,u-boot is in unpartitioned area before FAT (in case you use i.MX6it's 0x80000). It's there just to make your life easier.
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/295131", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/179161/" ] }
295,144
I have three files containing a sorted sequence of numbers, one per line : file1 123 file2 134 file3 15 I want to "align" these three files side-by-side like the following : file1 file2 file31 1 12 3 3 4 5 I've tried with sdiff but it only works with 2 files
You could process each file and print a line with some character e.g. X for every missing number in the sequence 1- max (where max is the last number in that file), paste the results then replace that character with space: paste \<(awk 'BEGIN{n=1};{while (n<$1) {print "X";n++}};{n=$1+1};1' file1) \<(awk 'BEGIN{n=1};{while (n<$1) {print "X";n++}};{n=$1+1};1' file2) \<(awk 'BEGIN{n=1};{while (n<$1) {print "X";n++}};{n=$1+1};1' file3) \| tr X ' ' If a certain value is missing from all files you'll get empty lines in your output (actually they're not empty, they contain only blanks). To remove them replace tr X ' ' with sed '/[[:digit:]]/!d;s/X/ /g' Also, if you need a header you can always run something like this first: printf '\t%s' file1 file2 file3 | cut -c2-
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/295144", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/179165/" ] }
295,170
I know this question has been asked multiple times but I didn't find the answer on those other questions. Here an Image to illustrate my point: Can you read the blue line without squinting? No? Me neither. I am running an ansible playbook in full verbose mode and need to read those logs with a playbook of 50+ tasks. Can anyone explain how can I change those colors? Questions I looked at where I didn't figure out a solution: Color1 Color2 Color3 Color4 ...
You can specify the color to use in ansible (at least you can with ansible 2.3.1.0).Open ansible.cfg and go to the section that says [colors]You should see something like this [colors]#highlight = white#verbose = blueverbose = green#warn = bright purple#error = red#debug = dark gray#deprecate = purple#skip = cyan#unreachable = red#ok = green#changed = yellow#diff_add = green#diff_remove = red#diff_lines = cyan Just uncomment the text type you want to change and specify the color you want.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/295170", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/179193/" ] }
295,199
I have a .pem file that after some formatting it shows like this: -----BEGINRSAPRIVATEKEY-----MIIEogIBAAKCAQEAoK3D4mMIRnzPaYqHidgpBnDDzLlcYYd0GoB0pQGyGSHDW7KO3K+VeJP90GhEZTEWJLp2N5DR/KT+5Vg7cgdx/GCCrnlbW0McP/IvkYAuWCgbzoXH9eE+kDRtAmurBYCk7OTOwQ26..........................LONG LONG LONG KEY................................QRRLFsXua9spUh0yPd163IZStKZMhZBPJfMaqbi1WF+j21DdYyS0qpaZQRjFzRLvGuXeGLZG/CODip10XRJMMXY0m14bqOTcqKTya/5PTJIjDWC22+soIjLy0ZjWKo9n05Oal2t4q35kbos=-----ENDRSAPRIVATEKEY----- And I obviously need to be like: -----BEGIN RSA PRIVATE KEY-----MIIEogIBAAKCAQEAoK3D4mMIRnzPaYqHidgpBnDDzLlcYYd0GoB0pQGyGSHDW7KO3K+VeJP90GhEZTEWJLp2N5DR/KT+5Vg7cgdx/GCCrnlbW0McP/IvkYAuWCgbzoXH9eE+kDRtAmurBYCk7OTOwQ26..........................LONG LONG LONG KEY................................QRRLFsXua9spUh0yPd163IZStKZMhZBPJfMaqbi1WF+j21DdYyS0qpaZQRjFzRLvGuXeGLZG/CODip10XRJMMXY0m14bqOTcqKTya/5PTJIjDWC22+soIjLy0ZjWKo9n05Oal2t4q35kbos=-----END RSA PRIVATE KEY----- How can I do it using awk or sed ? All the tutorials that I've found online shows how to do it for the whole text or for one type of pattern like aaaabbbaaacccc which I found confusing. I tried something like this: tr ' ' '\n' < test.pem | awk '/BEGIN\nRSA\nPRIVATE\n$/ { printf("%s\t", $0); next } 1' > test-format.pem But that failed. I don't know if it matters or not, but I'm doing this in a shell #!/bin/sh script in a python:3.5-alpine docker container. Any help is greatly appreciated.
One way with sed : sed -e '/^---/ { :1 $!N s/\n/ / /---$/!b1}' <file This approach does the job straight way: If line start with --- , then enter the code block Inside code block, we create a loop label named 1 We read N ext line of the input if current line is not the last line $ Replace newline \n with a space If next line does end with --- , break ! the loop, otherwise restart the loop b1
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/295199", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/138189/" ] }
295,207
So at my job I SSH from my CentOS machine to other local CentOS machines. We use an application that runs in both X11 and terminal. Some features are available exclusively in terminal and other features are exclusively in X11. The program auto detects if there is a X display to connect to and will use it if available. It would be nice to be able to quickly toggle between the two version of the application without having to put in an enhancement request. We have a large amount of desktop icons/short cuts without a -X or -Y flag. Is there any way to enable/disable X11 forwarding on a running SSH session that was started without the -X or -Y flag?
If you run with -X or -Y then this will set $DISPLAY on the remote end to point to the X-tunnel. Unsetting $DISPLAY will prevent X applications from talking to the X server.e.g. $ echo $DISPLAY localhost:10.0$ xdpyinfo | head -2name of display: localhost:10.0version number: 11.0$ DISPLAY= xdpyinfo | head -2xdpyinfo: unable to open display "".$ DISPLAY= xtermxterm: Xt error: Can't open display: xterm: DISPLAY is not set So with X tunneling enabled you should be able to "hide" it by unsetting $DISPLAY . Inside an SSH session you can type ~? to get a list of changes you can make. You can add/remove port forwarding via ~C but you can't easily change X tunneling because that would require running xauth and similar. The sequence of events would be to forwarding a remote port back to localhost:6000 (or whatever port your local X server is on), setting DISPLAY and adding xauth permissions - not so easy!
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/295207", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/174383/" ] }
295,238
I have a device that I need to connect to over SSH. The device is connected to my workstation via a direct ethernet connection. I'm attempting to assign the connected device an IP address somehow that I can SSH to, however all of the guides I'm finding have the user configure the IP from whatever device they're working with (namely Raspberry Pi's and so on). This is not something I can do with this device as I've no physical interface to work with. I've been recommended to setup a DHCP server on my workstation so it would take care of this for me, however I've no idea how to configure it and none of the guides I have followed have been helpful. With that approach, I seem to have been able to bind an IP to the interface the device is connected on, however SSHing to that IP just brings me back to my own machine. So my main question is: How do I assign an IP address to a device directly connected to my computer via ethernet cable without having any kind of access to the device (no interface, keyboard, monitor, etc). If the answer is to set up a DHCP server on my machine, how do I properly configure this and get an IP I can SSH to? For reference, I am using Ubuntu 16.04 with OpenSSH installed. The device is also running some flavor of Linux and has SSH software installed, but again there's no way to interact with it except through SSH. I also do not have access to my router, so plugging the device in there and letting the router do the work is not an option.
The link given by @steve as a comment is appropriate, but if you want to try something simple first just to see what the device does you can use dnsmasq , which is a simple dns and dhcp server. Install with sudo apt-get install dnsmasq . If this also enables and starts the server you need to stop and disable it. If, say, your device is on your ethernet interface eth2 , and you have done sudo ifconfig eth2 192.168.9.1 to set the interface ip address, then you can try: sudo dnsmasq -d -C /dev/null --port=0 --domain=localdomain --interface=eth2 --dhcp-range=192.168.9.2,192.168.9.10,99h which sets up a dhcp server in debug mode (-d), not as a daemon, with dns (port=0) able to offer addresses in the range .2 to .10, and to hold the same ones for 99hours. If your device broadcasts a request to discover an address you should see it, and the reply (offer): dnsmasq-dhcp: DHCPDISCOVER(eth2) 94:71:ac:ff:85:9d dnsmasq-dhcp: DHCPOFFER(eth2) 192.168.9.2 94:71:ac:ff:85:9d The numbers are the ip address assigned and the device's mac address. You may need to reset or power on the device if it has given up broadcasting. The device might reply to ping 192.168.9.2 and then you can try to ssh too.You can interrupt the dnsmasq once the address has been offered in this test and put the options in the standard dnsmasq config file and so on. You may also usefully run sudo tcpdump -i eth2 to see what packets pass.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/295238", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/179241/" ] }
295,241
I used this command to add i386 arch: sudo dpkg --add-architecture i386 And then immediately after without installing any packages I tried to remove the i386 arch like so: sudo dpkg --remove-architecture i386 And i got the error: dpkg: error: cannot remove architecture 'i386' currently in use by the database Solutions I have seen so far involve removing i386 packages, I haven't installed any, the ones that are installed are vital to the functioning of the OS. What do I do? EDIT, PLEASE READ THE FOLLOWING TO AVOID DESTROYING YOUR OS: Turns out that 64-bit Linux OSes already include the i386 arch, so the command sudo dpkg --add-architecture i386 didn't really do anything.
Run dpkg --get-selections | awk '/i386/{print $1}' And then if happy with them being removed, run apt-get remove --purge `dpkg --get-selections | awk '/i386/{print $1}'` And then retry the dpkg --remove-architecture i386
{ "score": 6, "source": [ "https://unix.stackexchange.com/questions/295241", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/122397/" ] }
295,263
Does the Bash language have a standard that dictates whether comments about the function should precede the function or be placed inside of it. I have seen scripts written both ways. # Comment preceding function.func1(){echo "example"} -or- func2() {# Comment inside of functionecho "example"}
In most programming languages, the comments that describe what the function does go before the function. You should probably do the same for bash. You should also use indentation: # function 1 commentfunc1() { echo "example"}
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/295263", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/86561/" ] }
295,274
I'm trying to change a single word on a specific line in a file, but I'm having some trouble connecting all together. Basically, on one line in my file there is a keyword 'firmware_revision', and on this line (and only this line) I want to replace the word 'test' with the word 'production'. So I can do this: grep 'firmware_revision' myfile.py | sed 's/test/production' This will pick out the line I want and perform the substitution, but I can't figure out how to get this new line into the original file to replace the old line. I obviously cannot just redirect it back to the file, so what should I do? Even if I use temporaries, by using grep to get just the line I need I lose all of the other data in the file, so I can no longer just redirect it all to a temp file then replace the original with the temp. Edit - Someone asked for more information Lets say I have a file full of lines like this [ ('key_name1', str, 'value1', 'Description'), ('key_name2', str, 'value2', 'Description'), ('key_name3', str, 'value3', 'Description'), ('firmware_revision', str, 'my-firmware-name-test', 'Firmware revision name')] now I want to write a script (ideally a one-liner) that will find the line that contains 'firmware_revision', and changes all instances of the word 'test' on that line to 'production'. The word 'test' might be in other places in that file and I do not want those changed. So to be clear, I want to change the above line to ('firmware_revision', str, 'my-firmware-name-production', 'Firmware revision name') How do I do this?
Try: sed -i.bak '/firmware_revision/ s/test/production/' myfile.py Here, /firmware_revision/ acts as a condition. It is true for lines that match the regex firmware_revision and false for other lines. If the condition is true, then the command which follows is executed. In this case, that command is a substitute command that replaces the first occurrence of test with production . In other words, the command s/test/production/ is executed only on lines which match the regex firmware_revision . All other lines pass through unchanged. By default, sed sends its output to standard out. You, however, wanted to change the file in place. So, we added the -i option. In particular, -i.bak causes the file to be changed in place with a back-up copy saved with a .bak extension. If you have decided that the command works for you and you want to live dangerously and not create a backup, then, with GNU sed (Linux), use: sed -i '/firmware_revision/ s/test/production/' myfile.py By contrast, on BSD (OSX), the -i option must have an argument. If you don't want to keep a backup, provide it with an empty argument. Thus, use: sed -i '' '/firmware_revision/ s/test/production/' myfile.py Edit In the edit to the question, the OP asks for every occurrence of test on the line to be replaced with production . In that case, we add the g option to the substitute command for a global (for that line) replacement: sed -i.bak '/firmware_revision/ s/test/production/g' myfile.py
{ "score": 6, "source": [ "https://unix.stackexchange.com/questions/295274", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/108328/" ] }
295,275
I'm trying to manipulate the editor of crontab but it's really really confusing.So I launch the creation of a new crontab with crontab -e Then the default editor opens. Now from there, it's seems to be LAGGING !!?? How do I move around in the editor ? How do I get "--INSERT--" to show and then write my "scritp" and then type :wq to write and save exit ? How can I go back to writing mode after pushing once esc or : ?
You can pick any editor you like by setting the $EDITOR variable before calling crontab -e e.g. $ EDITOR=emacs crontab -e will run emacs as your editor. If you have a favourite editor then you can select that. Many programs that call an external editor may also use this $EDITOR variable so you may find it useful to set it permanently in your .profile with export EDITOR=emacs Now crontab -e and others will automatically select this editor.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/295275", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/179255/" ] }
295,301
I have a data file ( data.txt ) with ~320 rows and ~1800 columns (1.9 MB), and I need to extract certain columns out (for all rows). The general layout of data.txt is as follows: ID Adipocyte - breast, donor2.CNhs11969.11327-117E4 ....HGNC:8888 0 .... HGNC:9999 123.92 ....HGNC:1000 9.31 .... I have a list of the columns I need to extract (in a file list.txt ), but this list is made up of only the CNhsXXXXX identifier in the column term (i.e. for the above example, the list would only contain CNhs11969 , not the whole term Adipocyte - breast, donor2.CNhs11969.11327-117E4 ). I've used grep for a list of rows before, but have not for columns. I had a look around but could not find a way to grep multiple columns with multiple terms. I'm very new to unix (I'm a biologist, little experience in computing), so I'm unsure if grep can do this. Any help would be appreciated. EDIT: My sample output would be only ~850 of the ~1800 columns (only those containing the terms in my list.txt file). Example: If my list contained only CNhs5006 and CNhs7021, I would only want columns containing those terms in the header. Example of the data.txt : ID XXXCNhs5006XXX XXXCNhs6025XXX XXXCNhs7021XXX XXXCNhs8095XXXHGNC:1111 1.23 1.53 9.21 0HGNC:2222 1.95 73.92 0 123.29 Example of the desired output: ID XXXCNhs5006XXX XXXCNhs7021HGNC:1111 1.23 9.21HGNC:2222 1.95 0 My list.txt is just a simple list of terms (1 column, ~850 rows, each row containing 1 search term). Example: CNhs1111CNhs2222CNhs3333CNhs4444
You can pick any editor you like by setting the $EDITOR variable before calling crontab -e e.g. $ EDITOR=emacs crontab -e will run emacs as your editor. If you have a favourite editor then you can select that. Many programs that call an external editor may also use this $EDITOR variable so you may find it useful to set it permanently in your .profile with export EDITOR=emacs Now crontab -e and others will automatically select this editor.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/295301", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/178020/" ] }
295,332
I have my input like below - [11/Jul/2016:13:40:43 +0000] "POST --" 200 - 7[11/Jul/2016:13:40:43 +0000] "POST --" 200 - 7[11/Jul/2016:13:40:47 +0000] "POST --" 200 - 7[11/Jul/2016:13:40:47 +0000] "POST --" 500 - 7[11/Jul/2016:13:41:48 +0000] "POST --" 200 - 7[11/Jul/2016:13:41:49 +0000] "POST --" 500 - 7[11/Jul/2016:13:42:12 +0000] "POST --" 500 - 7 I want the number of lines between the input 13:40 to 13:41 , in this case a count as 6. I tried below options echo sed -n '/^START_TIME/,/^END_TIME/ p' somelogfile.log | wc -lecho sed -n '/^13:40:43$/,/^13:41:43$/ p' somelogfile.log | wc -l but I get 1 all the time. Can someone check and let me know what is going wrong here ?
The echo is going to generate only one line and wc is counting this line. Note that the ending timestamp does not exist 13:41:43 , and the anchors used ( ^ and $ ) are too restrictive. Remove the echo and try this: sed -n '/13:40:43/,/13:41:49/p' somelogfile.log | wc -l
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/295332", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/179309/" ] }
295,355
I add the following line to the red-hat crontab in order to run the script /var/scripts/info_from_all_sites.bash every Friday at 00:00 night script should get as argument the file - /var/RT/names.txt so script will read all info from this file, 0 0 * * 5 /var/scripts/info_from_all_sites.bash /var/RT/names.txt 1>/dev/null 2>&1 my question is - is it OK to add the file as argument to the script in the crontab ? Or maybe I need to put the file with double quotes as 0 0 * * 5 /var/scripts/info_from_all_sites.bash "/var/RT/names.txt" ?
The echo is going to generate only one line and wc is counting this line. Note that the ending timestamp does not exist 13:41:43 , and the anchors used ( ^ and $ ) are too restrictive. Remove the echo and try this: sed -n '/13:40:43/,/13:41:49/p' somelogfile.log | wc -l
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/295355", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/153544/" ] }
295,363
ps aux | grep firefox Lists all processes having the string "firefox" ps aux | grep -v firefox Lists all the processes without the string "firefox" ps aux | grep -v grep | grep firefox ? What does this second grep does ? grep itself is a command then why we are grepping another grep ?
When you do a command such as ps aux | grep firefox Then the grep process itself may show in the output because the word you are looking for is present. e.g. on my machine I run chrome and the similar results: % ps aux | grep chromesweh 3384 0.0 0.0 11128 1024 pts/1 S+ 07:08 0:00 grep chromesweh 23698 0.0 0.0 6384 620 ? S Jul04 0:00 /usr/lib/chromi We can see process 3384 is the grep command and matches because the word chrome shows up. To avoid this some people then add a second | grep -v grep to remove that line. There is a cheat though... ps aux | grep '[f]irefox' grep '[f]irefox' matches exactly the same lines as grep firefox , but now the grep command will never match itself because the word doesn't literally appear on that command.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/295363", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/178935/" ] }
295,381
This maybe a weird question but please listen carefully Let's say I have a file as -rwxr-w--- user3 user2 4095 somefile Right now I'm in a user2 's shell(? is this right to say) and if I execute this 'somefile' with vi editor, I guess this somefile belongs to the user3 , So If I execute some command line in the vim, am I executing command in user3 's shell?
No, vim is not set user id (that is, it will not change effective userid). running a command line from vim will give you a shell (that is the word) as user2 . By the way, to edit the file you must either be user user3 belong to group user2 , merely being user2 is not enough. There used to be a bug in redhat 4.x (or still is) when running visudo, which allow you to run a shell as root. This was a light bug, as you must allready be in sudoers to run visudo.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/295381", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/176584/" ] }
295,400
I just installed Linux Mint 18 and began using the default pdf reader: xreader . However, sometimes when I leave a pdf open and compile it using pdflatex the program closes with this message: (xreader:25493): Gtk-CRITICAL **: gtk_widget_get_parent: assertion 'GTK_IS_WIDGET (widget)' failed (xreader:25493): GLib-GObject-WARNING **: invalid unclassed pointer in cast to 'EvWebView' This never happened with evince and I think it shouldn't happen. I could switch back to evince (assuming they're not the same program renamed) but I liked to X-apps initiative and would like to keep xreader . What might be causing this and how could I fix it? Cheers
No, vim is not set user id (that is, it will not change effective userid). running a command line from vim will give you a shell (that is the word) as user2 . By the way, to edit the file you must either be user user3 belong to group user2 , merely being user2 is not enough. There used to be a bug in redhat 4.x (or still is) when running visudo, which allow you to run a shell as root. This was a light bug, as you must allready be in sudoers to run visudo.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/295400", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/121808/" ] }
295,422
Solution for executing root commands as unprivileged user - sudo 'ing script - easily opens possibility of security breach and unexpected behavior and results (this is also true for any other solution such as binary wrapper with setuid ); It's clear that scripts added using visudo, like this www-data ALL=(ALL) NOPASSWD: /usr/local/sbin/mycommand should be readable , writable and executable only by root - which is both owner and group ( chown root:root mycommand; chmod 700 mycommand ) should have its parent directory ownership root:root with 755 mode should validate input - arguments and stdin - and reject and abort execution upon any invalid/unexpected data provided should use absolute instead of relative paths / aliases (?) Defaults env_reset in /etc/sudoers should be set (?help needed here) What else can be done to secure a sudo-powered script?
I'd amend your list of criteria for protecting a script a little. Given this - or a similar - entry in /etc/sudoers : www-data ALL=(ALL) NOPASSWD: /usr/local/sbin/mycommand we can state that the script: must be writeable only by the root user must be readable and executable by the root user must be in a hierarchy of directories that can only be written by root must validate its input "sufficiently" for the use, and reject anything else should have the smallest set of privileges necessary to carry out its task (not necessarily setuid root) should define its PATH before using any external commands should set all variables to a known value before using them should generate an audit trail to show not only when and how it was called, but also the resulting action (think logger ) Additionally, in many cases there is no real need for a script to run as root - it can run setgid, or even setuid to some other account. In the general case consider these options to avoid granting full root access to the script. For SELinux environments it may be possible to create a policy that prevents the script from doing anything unexpected. Capabilities such as CAP_NET_ADMIN are more finely grained than blanket root privileges and might also be worth considering. In the specific case you've outlined, where you want to validate a single IPv4 address and pass it to iptables , you might be able to get away with validating the IP address as a series of non-specific octets. In this case 444.555.666.999 might be accepted as plausible, knowing that iptables itself will reject anything that isn't a real IP address. At one extreme you might decide that matching the RE /^[0-9.]+$/ is enough to be happy passing the value to iptables . At the other, well there are plenty of answers on StackExchange and in other places that address the issue of validating an IP address. Some better than others. Special cases to consider are RFC1918 addresses, multicast addresses, and your own external IP address range. Oh, and the reserved block formerly known as Class E. Do you need IPv6 support? What will happen if your script is called hundreds of times a minute? Do you need to prepare for this eventuality? Will your iptables chain overflow? If you think you're going to need hundreds of rules in your chain it will be [more efficient to use the ipset extension to iptables rather than a linear list. Here's a good tutorial . In terms of protection, it allows you to build sets of thousands (if not tens of thousands ) of similar rules that can run without significantly slowing the traffic flowing through your rulesets. Suddenly your apparently straightforward requirement is quite complex.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/295422", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/68350/" ] }
295,495
I have a strange problem on my Linux Mint machine (with solid-state drive if that matters). Somehow the machine (on multiple occasions) gets different files, and different content for the same file, if I do "ls $PWD" instead of "ls ." or just "ls". That means I can write the file into the present working directory and pick up something different copying it from another directory. It's not $PWD set to the wrong thing, I can hand-type the directory name. I've checked this pretty carefully, but it does come and go. That makes it hard to make and to test production scripts and code. adam@RADIUM:/home/adam/cd2/adam_dev/rsim ==> ls .ClearPrice.cme Makefile.win data gfiles rsim5.tmp src zlibClearPrice.src ReadMe.txt err include rsimdone.txt toolsMakefile build g2f out scripts vs2013adam@RADIUM:/home/adam/cd2/adam_dev/rsim ==>adam@RADIUM:/home/adam/cd2/adam_dev/rsim ==> echo $PWD/home/adam/cd2/adam_dev/rsimadam@RADIUM:/home/adam/cd2/adam_dev/rsim ==> ls $PWDClearPrice.cmd Makefile.win err include scripts vs2013ClearPrice.src ReadMe.txt g2f out src zlib Makefile buildgfiles rsimdone.txt toolsadam@RADIUM:/home/adam/cd2/adam_dev/rsim ==>
This can happen if the current directory is renamed or moved while you're in it. For example: $ mkdir /tmp/X$ cd /tmp/X$ mkdir Y Z$ cd Y$ touch a b c d e f$ mv ../Y ../A$ mv ../Z ../Y$ echo $PWD/tmp/X/Y$ lsa b c d e f$ ls $PWD$ You can spot the difference in looking at the inode number of the directory: $ ls -ldi . $PWD26871815 drwxr-xr-x 2 sweh sweh 4096 Jul 12 17:27 ./26872035 drwxr-xr-x 2 sweh sweh 4096 Jul 12 17:27 /tmp/X/Y/ You can also detect this because /bin/pwd returns a different value $ /bin/pwd/tmp/X/A$ echo $PWD/tmp/X/Y Basically, $PWD is just where the shell thinks you are, not necessarily where you really are :-)
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/295495", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/179458/" ] }
295,525
A lot of people keep saying that Linux does not keep information about bind mounts, so there is no way to get a list of them and their sources. Here are some examples: from one of the the comments here : IIRC this information is not kept anywhere: after mount --bind , the two copies are equivalent, there isn't one that's more “original” than the other. After all there could be no original if you'd already unmounted /mnt . from an answer on this site : So the only way to remember what mounts were bind mounts is the log of mount commands left in /etc/mtab . A bind mount operation is indicated by the bind mount option (which causes the filesystem type to be ignored). But mount has no option to list only filesystems mounted with a particular set of sets of options. from a Debian bug report : This is intentional. Both mount points are fully equal in all ways sothe kernel does not keep any flags to differentiate them. The above is nonsense though. The tool findmnt is able to list the source paths of bind mounts (in the form of device[source-path] ; I'm also trying to get it to list just the source path and not the device). If the Linux kernel is to maintain a bind mount, then that information has to be stored somewhere , otherwise it couldn't know that /home is bound to /users . So where is this data? Is it stored in some obscure region in RAM? Does findmnt look in /proc somewhere?
You've misunderstood a little; the two mount points are equal in terms of permissions, flags, etc because the bind effectively redirects access from one path to another. But they are still distinct . If you look at /proc/self/mountinfo you'll see the kernel view of the mount world for this process (namespaces make things more complicated; there's not just one view of the mount table). man 5 proc will explain the format of this file, but you can see the tree hierarchy and where bind mounts have their "parent". This is the file that findmnt parses.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/295525", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/89807/" ] }
295,559
Is it possible to locate a path in the file system like what can be done for file names? For example I want to find all paths in system that include 'foo/bar', which may have the following result: /home/myname/test/ foo/bar /hello /var/www/site/ foo/bar
If you are unable to find the file with the below command then try updatedb for updating db used by locate command. locate -r foot/bar/ or # locate "/*/bar/avi"/foot/bar/avi find command can also do this find / -path */foot/bar* find / will search the whole system starting from /
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/295559", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/10867/" ] }
295,560
I have a time lapse of thousands of jpgs and would like to know if its possible to list only the shots taken during daylight hours? So it's not about listing the files between two dates, but listing the files between two hours on any date. eg: between 6am and 6pm. Can I do this using find?
If you are unable to find the file with the below command then try updatedb for updating db used by locate command. locate -r foot/bar/ or # locate "/*/bar/avi"/foot/bar/avi find command can also do this find / -path */foot/bar* find / will search the whole system starting from /
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/295560", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/179500/" ] }
295,573
My input is LOAD_DATE = 20072016 I want the output as LOAD_DATE = 20-07-2016 This is sample date.Date will come through LOG_DATE=echo ${LOG_FILE_NAME} |cut -d"." -f3 Sample dates "20072016,19072016,18072016" Here is what I am doing: LOG_DATE1=echo ${LOG_FILE_NAME} |cut -d"." -f3 LOG_DATE=`echo ${LOG_DATE1:0:2}-${LOG_DATE1:2:2}-${LOG_DATE1:4:4}` But this is giving me an error as "bad substitution"
If you are unable to find the file with the below command then try updatedb for updating db used by locate command. locate -r foot/bar/ or # locate "/*/bar/avi"/foot/bar/avi find command can also do this find / -path */foot/bar* find / will search the whole system starting from /
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/295573", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/179508/" ] }
295,612
For example: I have file a.txt and file b.txt . I want a link from a.txt to b.txt . If I open/read file a.txt , file b.txt should open/read. If I try something like ln -s a.txt b.txt I get an error because file b.txt exist. How can I create a link from a.txt to b.txt ?
You need to remove file b.txt previously with command rm b.txt , then create symbolic link with your command ln -s a.txt b.txt . You could use hard link from b.txt to a.txt , then execute ln a.txt b.txt , both a.txt and b.txt would point the same file on hard drive and removing a.txt doesn't remove file, which could be read through b.txt . With symbolic link from b.txt to a.txt removing a.txt remove file and b.txt symbolic link will be broken. More about hard links: https://en.wikipedia.org/wiki/Hard_link
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/295612", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/179553/" ] }
295,615
I'm trying to check if a user who connects to a linux server via SSH is authentificated using Active Directory (Centrify). In case he uses a local account (located in /etc/passwd ), I need to display a warning asking him to use his Active Directory account and then prompt login again. My first attempt was using PAM module pam_script inside /etc/pam.d/login to execute a script that checks if the current username exists in /etc/passwd whenever a user log in, display a warning if found and call the login command again. I added the following line to /etc/pam.d/login session required pam_script.so runas=root This line execute a script file located in /etc/security/onsessionopen which contain: #!/bin/shusername=$1if [ $(grep -c '^'$username':' /etc/passwd) = 1 ] then echo "Warning, please user your AD credentials" loginfi But the same scenario didn't work in /etc/pam.d/sshd .When using SSH the script does run but doesn't display text or prompt for login. Any thoughts ?Thank you
You need to remove file b.txt previously with command rm b.txt , then create symbolic link with your command ln -s a.txt b.txt . You could use hard link from b.txt to a.txt , then execute ln a.txt b.txt , both a.txt and b.txt would point the same file on hard drive and removing a.txt doesn't remove file, which could be read through b.txt . With symbolic link from b.txt to a.txt removing a.txt remove file and b.txt symbolic link will be broken. More about hard links: https://en.wikipedia.org/wiki/Hard_link
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/295615", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/179545/" ] }
295,680
I'm trying to open GNU Screen with the following command on my Mac OS: host:~ user$ screen The screen terminal opens but quickly dies with the error message: Cannot exec /bin/false: no such file or directory My terminal is configured to open bash shell on startup. I've tried setting the terminal shell to sh , it gives the same error. However, when I execute screen command as sudo , then the command succeeds. How do I resolve it for the normal user?
Have a look in your shell initialisation scripts for bash , or the screen config file, and see if there's anywhere false is being used with the explicit path /bin/false . On macOS, the false utility is located in /usr/bin , not in /bin . Failing that, see if your login shell for some odd reason is set to /bin/false , either by inspecting /etc/passwd or looking at the "Advanced Options" in the "User & Groups" section of the System Preferences (you get these by right-clicking on your user in the list of user accounts, and you may change the shell here too). Someone may have unthinkingly followed a tutorial/HOWTO which sets up a user with /bin/false as their default shell. When you run screen with sudo you use root 's shell/screen init files. This is why that works.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/295680", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/22626/" ] }
295,702
I have a gzip archive with trailing data. If I unpack it using gzip -d it tells me: " decompression OK, trailing garbage ignored " (same goes for gzip -t which can be used as a method of detecting that there is such data). Now I would like to get to know this garbage, but strangely enough I couldn't find any way to extract it. gzip -l --verbose tells me that the "compressed" size of the archive is the size of the file (i.e. with the trailing data), that's wrong and not helpful. file is also of no help, so what can I do?
Figured out now how to get the trailing data. I created Perl script which creates a file with the trailing data, it's heavily based on https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=604617#10 : #!/usr/bin/perluse strict;use warnings; use IO::Uncompress::Gunzip qw(:all);use IO::File;unshift(@ARGV, '-') unless -t STDIN;my $input_file_name = shift;my $output_file_name = shift;if (! defined $input_file_name) { die <<END;Usage: $0 ( GZIP_FILE | - ) [OUTPUT_FILE] ... | $0 [OUTPUT_FILE]Extracts the trailing data of a gzip archive.Outputs to stdout if no OUTPUT_FILE is given.- as input file file causes it to read from stdin.Examples: $0 archive.tgz trailing.bin cat archive.tgz | $0END}my $in = new IO::File "<$input_file_name" or die "Couldn't open gzip file.\n";gunzip $in => "/dev/null", TrailingData => my $trailing;undef $in;if (! defined $output_file_name) { print $trailing;} else { open(my $fh, ">", $output_file_name) or die "Couldn't open output file.\n"; print $fh $trailing; close $fh; print "Output file written.\n";}
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/295702", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/117599/" ] }
295,715
If I have started a process, and it spends more time than I anticipated, and I regret not having said rm foo & rather than rm foo , can I do something to drop it into the background?
In pretty much any shell you're likely to be using, you should be able to press control-Z to suspend the process and then use the bg command to resume it in the background. e.g. $ sleep 1000^Z[1] + Stopped sleep 1000$ bg[1] sleep 1000&$ jobs[1] + Running sleep 1000$ Note that some jobs (e.g. those that ask for user input) will not run in the background and will stop, waiting to be brought back to the foreground ( fg ). (There are shells and situations where this doesn't work, but they tend to be highly specialised - eg embedded systems - or very very old versions of unix).
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/295715", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/134690/" ] }
295,718
I have file with number of columns for example input file 12 15 27 5 6 48 19 16 25 17 23 37 etc I want to count all the numbers ( X ) in column 2 for example that fulfill the following condition 6 <= X < 20 so the result would be 3 corresponding to the numbers 15 , 6 and 16 .
This is easy enough in a tool like awk awk '$2>=6 && $2<20 { tot++ } END { print +tot}' If you want to sum them then awk '$2>=6 && $2<20 { tot += $2 } END { print +tot}'
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/295718", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/112129/" ] }
295,806
Why are shell scripts are so hard to develop? In NodeJS I could simply do: require('./script') and it will always require script relative to the current script. But if I try that in shell/bash: ./script.sh it will look for script relative to cwd ( pwd ). Seems the dot means cwd ( pwd ) and not the directory where current script is located as I was expecting. line 8: ./script.sh: No such file or directory How can I execute a script relative to the directory where the current executing script is located? I have tried /bin/bash script.sh but I get the error: /bin/bash: script.sh: No such file or directory Then I tried script.sh Got this error line 8: script.sh: command not found Only the following solution worked fine, but the problem is that it is unreadable: $("$(dirname "$(realpath "$0")")/script.sh")
Another variant to get script dir: DIR="$(cd "$(dirname "$0")" && pwd)" then you can call script with $DIR/script.sh
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/295806", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/85409/" ] }
295,833
While installing Oracle DB in linux machine, I face a problem like swap space is not sufficient. How can I increase the swap space?
In linux there is swap space in partitions or in files. Once the disk is partitioned the easiest way to grow the swap space is creating a swap file in one of your partitions. Type df -h and check which one has free space. Say you find free GB in /home : First create a file. In this example we add around 1GB of space. Login as root in a terminal. # dd if=/dev/zero of=/home/swap1 bs=1024 count=1024000 Make this file owned by the root user and allow only root to read and write to it: # chown root:root /home/swap1# chmod 0600 /home/swap1 Turn it into a swap file # mkswap /home/swap1 Try it right now. This activates the new swap space without rebooting: # swapon /home/swap1 Add it to the fstab file so it works when you reboot. Be carefull with the next command, do not forget there are two > echo "/home/swap1 none swap sw 0 0" >> /etc/fstab Check the new space is being used typing this: # swapon --show
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/295833", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/179677/" ] }
295,871
Its usually been seen that if an executable is cat ed, provided that its a huge file, it keeps on changing the title of the 'PuTTY application until its done printing the binary to the STDOUT with those weird characters, prefixing strace did not seem to help in knowing. What all goes on there, which makes this happen? Just curious.
As improbable as it might seem, PuTTY does this in response to a combination of characters. PuTTY recognizes many (by no means all ) of the escape sequences used for xterm , Linux console and some less familiar terminals. One of PuTTY's developers compiled a list of all of the ones that might be of interest, about 650 items. You can find copies here and there named "all-escapes.txt" , beginning thus: # This file is hoped to document all the escape sequences supported by# terminals that are vaguely compliant with ECMA-48 and friends.# Changes should be submitted to <[email protected]># It includes everything from:# <URL:http://www.cs.utk.edu/~shuford/terminal/dec_vt220_codes.txt> 1999-05-16# <URL:http://www.cs.utk.edu/~shuford/terminal/vt100_reference_card.txt># 1993-02-01# <URL:http://www.cs.utk.edu/~shuford/terminal/vt100_codes_news.txt>1998-09-18# <URL:http://www.cs.utk.edu/~shuford/terminal/ansi_dec_controls_news.txt># 1999-05-16# <URL:http://www.cs.utk.edu/~shuford/terminal/xterm_controls.txt> 1999-10-12# <URL:http://www.cs.utk.edu/~shuford/terminal/color_control_news.txt># 1999-11-13# ECMA-48 5th Ed. control functions (section 8.3, annex F)# Linux console_codes(4)# SunOS 5.7 wscons(7D)# UnixWare 7 display(7)# IRIX 6.5.5 xwsh(1G)# VT220 Reference manual (<URL:http://vt100.net/docs/vt220-rm/>, EK-VT220-RM)# <URL:http://vt100.net/ctrlseq_dec.html> 1999-11-24# <URL:http://vt100.net/ctrlfunc_dec.html> 1999-12-01# <URL:http://www.wyse.com/service/support/kbase/SEQwt.asp?Q=9> (wy75)# 1999-07-19# <URL:ftp://ftp.cs.cmu.edu/afs/cs/user/ralf/pub/rbcom346.zip#TERM-EMU.DOC># 1999-09-13# <URL:http://www.itscj.ipsj.or.jp/ISO-IR/2-1.htm> 1999-04-19# <URL:http://www.itscj.ipsj.or.jp/ISO-IR/2-2.htm> 2004-09-27# <URL:http://www.itscj.ipsj.or.jp/ISO-IR/2-3.htm> 2004-09-27# <URL:http://www.itscj.ipsj.or.jp/ISO-IR/2-8-1.htm> 1999-04-19# <URL:http://www.itscj.ipsj.or.jp/ISO-IR/2-8-2.htm> 2001-05-10# iBCS2 description in ESR's termtypes.master version 10.2.7# Reflection Terminal Reference Manual for ADDS, ANSI, DG, VT, WYSE, and# Unisys Hosts; Version 7.0; September 1998; published by WRQ Inc.# DEC Terminals and Printers Handbook 1985 EB 26291-56 (Appendices C, E, and G)# OpenServer 5.0.6 screen(HW)# X Consortium Compound Text Encoding Version 1.1 For whatever reason, they disliked the notion of referring directly to the documentation for Linux and xterm, but used secondary sources. The title strings recognized by PuTTY begin with one of these choices: ANSI 7-bit OSC ( escape ] ), or ANSI 8-bit OSC (octal 235 ) followed by 0 , 1 , 2 , 2 1 (ASCII digits) or L , a semicolon, and the title text , and end with one of these choices: ANSI 7-bit string terminator ( escape \ ), or ANSI 8-bit string terminator (octal 234 ), or ASCII BEL (7, used by xterm) As an aside, it will stop processing the title escape if it sees an ASCII carriage return or line-feed. While a "big" file might seem to be random enough, it's likely that your file contains some bias in the form of tables, etc. Otherwise it would not repeatedly update the title as described. It might be interesting to construct a program which detected latent title-strings, so that you could find those without having to reset your terminal (or possibly stop it entirely). Further reading: console_codes - Linux console escape and control sequences XTerm Control Sequences ECMA-48: Control Functions for Coded Character Sets
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/295871", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/74910/" ] }
295,883
I'm working on some script that being run by rc.local at startup, and I noticed that output redirection works quite strange. If I write something like echo "foo" >&1 , it ends up in syslog, and all is okay. But when I write echo "foo" >>/dev/stdout , or echo "foo" >>/proc/self/fd/1 , I got an error saying that there is no such device or address. Further investigation revealed that /proc/self/fd/1 was in fact a socket.Including ls -l /proc/self/fd in rc.local prints the following: lr-x------. 1 root root 64 Jul 14 05:28 0 -> /dev/nulllrwx------. 1 root root 64 Jul 14 05:28 1 -> socket:[18485]lrwx------. 1 root root 64 Jul 14 05:28 2 -> socket:[18485]lr-x------. 1 root root 64 Jul 14 05:28 255 -> /etc/rc.d/rc.local The described behaviour can be easily reproduced with nc . First, find out which file descriptor binds to socket. You can do it by issuing nc -l -p 25566 -c "ls -l /proc/self/fd" in first terminal and then telnet localhost 25566 in other terminal. In my case it was 5-th descriptor. Okay. Then, to reproduce the issue, in first terminal: nc -l -p 25566 -c "echo 'hello' >&5" in second terminal: telnet localhost 25566 You shall see "hello" in second terminal output between telnet messages about connection being established and closed. Now the case with file descriptor pseudo-file from /proc : first terminal: nc -l -p 25566 -c "echo 'hello' >/proc/self/fd/5" second terminal: telnet localhost 25566 Now second terminal just contains telnet messages about connection established and immediately closed, and first terminal shows an error: sh: /proc/self/fd/5: No such device or address . Edit: OS is Fedora 23 i686 server So, the question. What's the difference between >&1 and >/proc/self/fd/1 ? And is there some universal and reliable way to redirect output to some file, which corresponds exactly to current standard output? Thank you. Edit 2: For clarity, exact input/output for Fedora 23 i686 for above case: Terminal 1 | Terminal 2$ nc -l -p 25566 -c 'ls -go /proc/self/fd' | | $ telnet localhost 25566 | Trying ::1... | Connected to localhost. | Escape character is '^]'. | total 0 | lr-x------ 1 64 Jul 14 08:56 0 -> pipe:[19687] | l-wx------ 1 64 Jul 14 08:56 1 -> pipe:[19688] | lrwx------ 1 64 Jul 14 08:56 2 -> /dev/tty2 | lr-x------ 1 64 Jul 14 08:56 3 -> pipe:[19687] | lr-x------ 1 64 Jul 14 08:56 4 -> /proc/1285/fd | lrwx------ 1 64 Jul 14 08:56 5 -> socket:[19686] | l-wx------ 1 64 Jul 14 08:56 7 -> /pipe:[19688] | Connection closed by foreign host.$ nc -l -p 25566 -c "echo 'hi' >&5" | | $ telnet localhost 25566 | Trying ::1... | Connected to localhost. | Escape character is '^]'. | hi | Connection closed by foreign host.$ nc -l -p 25566 -c "echo 'hi' >/proc/self/fd/5" | | $ telnet localhost 25566 | Trying ::1... | Connected to localhost.sh: /proc/self/fd/5: No such device or address | Escape character is '^]'. | Connection closed by foreign host.$ | $
Use >&N . It's portable and as you saw, actually works with sockets. The only reason you would ever use /proc/self/fd is you are running a program that expects a file name and can't be told to use an already open file descriptor. E.g. the <(cmd...) redirection uses that, since almost all command line utilities can open a file pointed to by name, but not all support preopened file descriptors directly. Your shell can use pre-existing file descriptors, though, so no need to go through /proc . Also, /proc/NNN/fd/ is specific to Linux, and requires that you have a mounted /proc . On my Linux boxes, /dev/stdout , /dev/fd/* and others are symlinks to /proc/self/fd/* etc., so they require /proc too. On other Unixes, they might be different. According to the answers to an older question /dev/stdout are specifically listed as outside POSIX. As for why the redirection doesn't work as you tried: Trying out with strace , the difference between the two is that for a >&N redirection, bash calls dup() on the file descriptor, and for >/proc/self/fd/N it just tries to open it as an ordinary file with open() . Apparently proc doesn't support opening new copies of sockets like that, so the call fails. Stream sockets are pretty much point to point links, so prohibiting opening of a new copy doesn't seem too unnatural. But why it works for pipes or with a dup , I couldn't tell. $ ls -l /proc/self/fd/3lrwx------ 1 itvirta itvirta 64 Jul 14 18:24 /proc/self/fd/3 -> socket:[168157]$ strace bash -c "echo foo >>/proc/self/fd/3" 2>&1 | grep open.*proc/selfopen("/proc/self/fd/3", O_WRONLY|O_CREAT|O_APPEND, 0666) = -1 ENXIO (No such device or address) Also this answer has some information about the portability of /proc/NNN/fd
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/295883", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/101764/" ] }
295,965
Let's say I'm in a directory which has some subdirectories, dir1 , dir2 , and dir3 . Each of these directories have a file foo and I would like to execute the same command on each foo in each of the directories and have that command executed from inside that directory. If I were to do it "by hand", it would look something like this: cd dir1(execute on foo)cd ../dir2(execute on foo)cd ../dir3(execute on foo) It is imperative that the command be executed from each of the directories . foo is a batch scheduling script (for HTCondor, if you care to know) and must be executed from each subdirectory so that the output of the runs started by the scheduling scripts will end up in each subdirectory. The question " Find a file and execute a command in the file's directory ", as far as I can tell, does not answer my question. The first answer to that question is more of a workaround which will not work in my case, and the second answer does not have enough of an explanation for me to know how to use it.
Assuming your find supports it, use the -execdir option instead of -exec find . -name 'foo' -execdir pwd \; If it doesn't, please provide details of your platform and/or distribution (as appropriate).
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/295965", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/42001/" ] }
295,977
I have a file as the following input file0.0 4 6 5 1 2 9 4 5 1 ..... 0.250.5 3 1 1.0 3 7 8 2 1.5 3 3 3 4 6 4 5 2.0 2.5 6 7 6 9 I want to delete all lines that have only one value in the line so the result will be like this out file 0.0 4 6 5 1 2 9 4 5 1 ..... 0.5 3 1 1.0 3 7 8 2 1.5 3 3 3 4 6 4 5 2.5 6 7 6 9
One approach using awk . Uses NF (number of fields) to only print the lines where number of fields is greater than 1. awk <oldfile >newfile 'NF>1' Example awk <oldfile >newfile 'NF>1'cat newfile0.0 4 6 5 1 2 9 4 5 1 .....0.5 3 11.0 3 7 8 21.5 3 3 3 4 6 4 52.5 6 7 6 9
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/295977", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/112129/" ] }
295,999
I'm trying to learn the POSIX standard. When using Unix, I have /bin , /etc , /dev , /media , and usually /opt , but is that standardized or up to your spec implementation? Could there be many directories in the root, or is it limited by the standard?
According to The Open Group's published standard , the only required directories are: / /dev , which contains console , null , and tty /tmp , guaranteed writable but not necessarily preserved. The Linux Foundation maintains a Filesystem Hierarchy Standard (FHS) which extends this to include the directories you will typically see on a Linux system: /bin : Essential user command binaries /boot : Static files of the bootloader /dev : Device files /etc : Host-specific system configuration /home : User home directories (optional) /lib : Essential shared libraries and kernel modules /lib<qual> : Alternate format essential shared libraries (optional) /media : Mount point for removable media /mnt : Mount point for a temporarily mounted filesystem /opt : Add-on application software packages /root : Home directory for the root user (optional) /run : Run-time variable data /sbin : System binaries /srv : Data for services provided by this system /tmp : Temporary files As well as the /usr hierarchy and the /var hierarchy The FHS was designed to be as generic as possible, to allow for incorporation in any UNIX system. The additional directories are likely to exist in any reasonable system, but this is not mandated by POSIX. However, note that The Open Group also states that Strictly conforming applications shall not assume the ability to create files in any of these directories, unless specified below. Since directories are really just files, this implies that a strictly conforming application will not create any files or directories at the root level. Therefore, POSIX does not necessarily limit what a distribution may place at the root level, but does seem to state that an application conforming to its specification cannot assume that it will be able to.
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/295999", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/9115/" ] }
296,041
In gvim editor how to split the editor window horizontally? so that includes two files and can see simultaneously?
From command line: open specified files as horizontal splits gvim -o report.log power.log area.log open specified files as vertical splits gvim -O report.log power.log area.log Within the editor open file for editing in new horizontal split screen :split filename:sp filename open file for editing in new vertical split screen :vsplit filename:vs filename Check out :h windows.txt for more help
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/296041", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/179851/" ] }
296,086
to find the PID of the process to kill use : pgrep <process command> I then use the kill command to kill the PID returned by pgrep <process command> kill <PID> Can these commands be combined into one so can kill the PID or PID's returned by pgrep <process command> ? Or is there a method kill multiple processes by command name ? Something like : kill(pgrep <name of process>)
You can use pkill: pkill httpd You may also want to use process substitution(although this isn't as clear): kill $(pgrep command) And you may want to use xargs : pgrep command | xargs kill
{ "score": 6, "source": [ "https://unix.stackexchange.com/questions/296086", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/65628/" ] }
296,096
I have a 32bit ubuntu linux install on an hp stream 7 tablet. For the sake of long term support I would like to install 64bit ubuntu linux on this device. The tablet has a 64 bit intel baytrail processor. Unfortunately it also has 32bit efi. As things stand, update grub installs an efi bootloader that works perfectly. If I upgrade the install to 64bit will this still be the case? I know that debian has support for this from Jessie onwards. Will ubuntu also support this weird setup?
It is certainly possible, because I am right now typing this answer from a 64-bit Ubuntu system on a machine that exclusively boots with 32-bit UEFI. Last year, I had to boot from GRUB command line after running the installer and then compile GRUB using instructions here by Lopaka (now updated) But with Ubuntu 16.04 I was amazed to find it installed the correct, 32-bit version of GRUB without any special intervention on my part :) I suspect this is because both versions now get installed to the ESP... have a look: /boot/efi/EFI├── Boot│   ├── bootia32.efi│   ├── bootx64.efi│   └── bootx64.efi.grb├── grub│   ├── grub.efi│   └── grubia32.efi├── grub_uefi│   ├── grub.efi│   └── grubia32.efi├── Microsoft│   └── Boot│   ├── bootmgfw.efi│   ├── bootmgfw.efi.grb│   ├── bootx64.efi│   └── bootx64.efi.grb└── ubuntu ├── fw ├── fwupx64.efi ├── grub.cfg ├── grub.efi ├── grubia32.efi ├── grubx64.efi ├── MokManager.efi └── shimx64.efi But the ESP remains somewhat mysterious to me, I admit... I must warn that others haven't found it as easy to achieve this precarious state of harmony as I have... Some people with my device, for example, find that GRUB will not install and so the installation will not complete. However, if that happens it is possible to exclude GRUB from the installation and fix it by booting a live session and installing 32-bit GRUB by a chroot method. I'm not sure how you'd manage this with a tablet. TL;DR It is possible, but not at all guaranteed to be free from complications...
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/296096", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/156756/" ] }
296,098
My local machine does not have a public IP and the IT department cannot setup an NAT for me, I want to setup a proxy on my remote public server which will forward the request to my local server. I try using privoxy + ssh, but it says invalid header. Step 1:open a ssh tunel by ssh -nNT -R 8081:localhost:8080 [email protected] Step 2:On the remote machine, configure a privoxy config, I tried forward-socks5 / 127.0.0.1:8081 .listen-address 0.0.0.0:8080 and forward / 127.0.0.1:8081listen-address 0.0.0.0:8080 both said invalid header in browser
It is certainly possible, because I am right now typing this answer from a 64-bit Ubuntu system on a machine that exclusively boots with 32-bit UEFI. Last year, I had to boot from GRUB command line after running the installer and then compile GRUB using instructions here by Lopaka (now updated) But with Ubuntu 16.04 I was amazed to find it installed the correct, 32-bit version of GRUB without any special intervention on my part :) I suspect this is because both versions now get installed to the ESP... have a look: /boot/efi/EFI├── Boot│   ├── bootia32.efi│   ├── bootx64.efi│   └── bootx64.efi.grb├── grub│   ├── grub.efi│   └── grubia32.efi├── grub_uefi│   ├── grub.efi│   └── grubia32.efi├── Microsoft│   └── Boot│   ├── bootmgfw.efi│   ├── bootmgfw.efi.grb│   ├── bootx64.efi│   └── bootx64.efi.grb└── ubuntu ├── fw ├── fwupx64.efi ├── grub.cfg ├── grub.efi ├── grubia32.efi ├── grubx64.efi ├── MokManager.efi └── shimx64.efi But the ESP remains somewhat mysterious to me, I admit... I must warn that others haven't found it as easy to achieve this precarious state of harmony as I have... Some people with my device, for example, find that GRUB will not install and so the installation will not complete. However, if that happens it is possible to exclude GRUB from the installation and fix it by booting a live session and installing 32-bit GRUB by a chroot method. I'm not sure how you'd manage this with a tablet. TL;DR It is possible, but not at all guaranteed to be free from complications...
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/296098", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/104992/" ] }
296,100
Apparently I don't know all the output destinations that are available for use. I know about stdout ( &1 ) and stderr ( &2 ). However, after redirecting both descriptors, I sometimes still get some output in my console! The easiest example I can think of is GNU Parallel; Each time I use it, I see a citation notice. Even when I do &2>1 > file , I still see the notice. And the same applies to emerge : When I run emerge and there are some problems, some informations aren't printed to stdout nor stdin , since I redirect them and they still get through. I mostly solve these problems by using script , but I am still wondering what's causing this issue.
The syntax you used is wrong. cmd &2>1 >file will be split down as cmd &2>1 >file This will: Run cmd as a background job with no redirections In a separate process (without a command!) will redirect stderr to a file literally called 1 and redirect stdout to file The syntax you want is: cmd >file 2>&1 The order of operations is important. This will: Redirect stdout to file Redirect stderr to &1 - ie the same filehandle as stdout The result is that both stderr and stdout will be redirected to file . In bash , a simpler non-standard (and so I don't recommend it, on portability grounds) syntax of cmd &> file does the same thing.
{ "score": 6, "source": [ "https://unix.stackexchange.com/questions/296100", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/129998/" ] }
296,136
I have to delete one particular file in each directory. Example: MKRUW, DKRUW, TKRUW In each of these directories I need to enter MKRUW/default/file and delete .dat files.
The syntax you used is wrong. cmd &2>1 >file will be split down as cmd &2>1 >file This will: Run cmd as a background job with no redirections In a separate process (without a command!) will redirect stderr to a file literally called 1 and redirect stdout to file The syntax you want is: cmd >file 2>&1 The order of operations is important. This will: Redirect stdout to file Redirect stderr to &1 - ie the same filehandle as stdout The result is that both stderr and stdout will be redirected to file . In bash , a simpler non-standard (and so I don't recommend it, on portability grounds) syntax of cmd &> file does the same thing.
{ "score": 6, "source": [ "https://unix.stackexchange.com/questions/296136", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/173191/" ] }
296,141
Many questions like 'How to type the double-quote char (")?' are being asked, and we don't want to clutter our community with the same answer (Type it as \" if not enclosed in ' s, " if enclosed in ' s.) So, the question is here. You can't type special chars into a terminal like normal ones, e.g. this command will fail: echo Updates (11) So, how to type in these chars in the terminal as if they were normal ones? !#$^&*?[](){}<>~;'"\|<space><tab><newline>
That very much depends on the shell. Check your shell manual for details. Also note that some characters are only special in some contexts. For instance, in most shells, * and ? are only special in list contexts,in POSIX or csh-like shells, ~ is only special at the beginning of a word or following some characters like : . Same for = in zsh . In some shells, [ is only special when matched (with some restrictions) by a ] . In some shells like bash or yash , special characters like blank token delimiters also vary with the locale. The quoting operators (to remove the special meaning of those characters) also vary greatly between shells. Bourne-like shells A summary for Bourne-like shells (that is the shells that have been known to be called sh on some system or another since the 80s): Bourne shell Special characters: "'&|;()^`<>$ , space, newline and tab are special in simple command lines when not quoted. # (except in early version) is special at the beginning of a line or following an unquoted space, tab or &|()^<>;` . { and } are only special in that they are shell keywords (so only words in command position). *?[ are special as globbing operators, so only in list contexts. In the case of [ , it's [...] that is the globbing operator, either [ or ] only need to be quoted to remove the special meaning. = is special when in contexts where it's treated as an assignment operator. That is, in a simple command, for all words that do not follow an argument (except after set -k ). Quoting operators \ quotes all special characters except newline ( \<newline> is a way to continue a long logical line onto the next physical line, so that sequence is removed). Note that backticks add extra complexity as within them, \ is used first to escape the closing backtick and help the parser. Inside double quotes, \ may only be used to escape itself, " , $ and ` ( \<newline> is still a line-continuation). Inside a here-document, same except for " . \ is the only way to escape characters inside here documents. "..." double-quotes escape all characters but itself, \ , $ and ` . '...' single quotes escape all characters but itself. POSIX shells POSIX shells behave mostly like the Bourne shell, except that: ^ is no longer a special character ~ is special in some contexts { is allowed to be special so should be quoted. ksh like POSIX except that: {string} is special if string contains an unquoted , (or .. in some cases and with some versions). ksh93 has an additional special quoting operator: $'...' with complex rules. That operator is also found (with some variations) in bash , zsh , mksh and FreeBSD and busybox sh . ksh93 also has a $"..." quoting operator that works like "..." except that the string is subject to localisation (could be configured so it translates to the language of the user). mksh ignores the $ in $"..." . since ksh93r , ksh93 supports csh-style history expansion (not enabled by default) with -H / -o histexpand in interactive shells which makes ^ at the beginning of commands and ! special. ! is then special in some contexts (not when followed by space or TAB nor in here documents) and is not escaped by double quotes. Only backslash (not within double-quotes where \ removes ! its special meaning but is not otherwise removed) and single quotes escape it. bash like ksh93 but: in single-byte character locales, all blank (according to the locale) characters are considered as delimiters (like space or tab). In effect, that means you should quote all bytes with the 8th bit set in case they may be a blank character in some locale. csh history expansion is enabled by default in interactive instances, with the same notes as on ksh93 above except that in newer versions of bash , ! is also not special sometimes, when followed by a " . like in csh, % at the start of a command is used to manipulate jobs. %1 puts job number one in foreground instead of running the %1 command. Same with %1 & to put it in background... zsh like ksh93 but: same note as for bash for csh history expansion, except that backslash can be used to escape ! inside double quotes like in csh. = is special as the first character of a word ( =ls expands to /bin/ls ). same note as for bash about % in command position. { and } can also open and close command groups when not delimited (as in {echo text} works like Bourne's { echo text;} ). except for [ alone, [ needs quoted even if not closed with a ] . With the extendedglob option enabled, # , ^ and ~ are globbing operators. With the braceccl option, {non-empty-string} is special. $"..." is not supported. as a special quirk, ? is not special when following a % (even quoted or expanded) at the start of a word (to allow the %?name job specification) a rcquotes option (not enabled by default) allows one to enter single quotes as '' inside single quotes à la rc (see below). yash like POSIX except that. all blank characters are considered as delimiters. With the brace-expand option, implements zsh-style brace expansion. same note as for bash abd zsh about % in command position (except when in POSIX mode). For all shells, there are some special contexts where quoting works differently. We've already mentioned here documents and backticks, but there's also [[...]] in ksh and a few other shells, POSIX $((...)) , case constructs... Also note that quoting can have other side-effects when it comes to expansions (with double-quotes), or when applied to here document delimiters. It also disables reserved words and affects alias expansion. Summary In Bourne-like shells, !#$^&*?[(){}<>~;'"`|= , SPC, TAB, NEWLINE and some bytes with the 8th bit set are or may be special (at least in some contexts). To remove the special meaning so they be treated literally, you use quoting. Use: '...' to remove the special meaning of every character: printf '%s\n' '\/\/ Those $quoted$ strings are passed literally assingle arguments (without the enclosing quotes) to `printf`' \ to remove the special meaning of one character only: printf '<%s>\n' foo bar\ baz #comment Above, only the space character preceded by a \ is passed literally to printf . The other ones are treated by the shell as token delimiters. use "..." to quote characters while still allowing parameter expansion ( $var , $# , ${foo#bar} ...), arithmetic expansion ( $((1+1)) , also $[1+1] in some shells) and command substitution ( $(...) or the old form `...` . Actually, most of the time, you do want to put those expansions inside double quotes in any case . You can use \ within "..." to remove the special meaning of the characters that are still special (but only them). if the string contains ' character, you can still use '...' for the rest and use other quoting mechanisms that can quote ' like "'" or \' or (where available) $'\'' : echo 'This is "tricky", isn'\''t it?' Use the modern $(...) form of command substitution. Only use the old `...` for compatibility with the Bourne shell, that is to very old system, and only in variable assignments, as in don't use: echo "`echo "foo bar"`" Which won't work with the Bourne shell or AT&T versions of ksh. Or: echo "`echo \"foo bar\"`" Which will work with Bourne and AT&T ksh, but not with yash ( 2020 edit: only in version 2.41 and earlier though, it's since been changed in 2.42 / bug report / commit ), but use: var=`echo "foo bar"`; echo "$var" which will work with all. Nesting them portably with double quotes is also impossible, so again, use variables. Also beware of the special backslash processing: var=`printf '%s\n' '\\'` Will store only one backslash inside $var , because there's an extra level of backslash processing (for \ , `, and $ (and also " when quoted except in yash )) within backticks so you need either var=`printf '%s\n' '\\\\'` or var=`printf '%s\n' '\\\' instead. Csh family csh and tcsh have a significantly different syntax, though there is still a lot in common with the Bourne shell as they share a common heritage. Special characters: "'&|;()^`<>$ , space, newline and tab are special everywhere when not quoted. # (csh is the shell that introduced # as the comment leader) is special at the beginning of a script or following an unquoted space, tab or newline. *?[ are special as globbing operators so in list contexts {anything} is special except for the special case of a standalone {} (csh is the shell that introduced brace expansion). ! and ^ are special as part of history expansion (again, a csh invention), and quoting rules are special. ~ (tilde expansion also a csh invention) is special in some contexts. Like in bash, zsh, yash, % in command position is used to manipulate jobs (again a csh invention). Quoting operators They are the same as for the Bourne shell, but the behaviour differs. tcsh behaves like csh from the syntax point of view, you'll find that many versions of csh have nasty bugs. Get the latest version of tcsh to get a roughly working version of csh. \ escapes a single character except newline (same as for the Bourne shell). It's the only quoting operator that can escape ! . \<newline> doesn't escape it but transforms it from a command separator to a token separator (like space) "..." escapes all characters except itself, $ , ` , newline and ! . Contrary to the Bourne shell, you can't use \ to escape $ and ` inside "..." , but you can use \ to escape ! or newline (but not itself except when before a ! or newline). A literal ! is "\!" and a literal \! is "\\!" . '...' escapes all characters except itself, ! and newline. Like for double quotes, ! and newline can be escaped with backslash. command substitution is only via the `...` syntax and can hardly be used reliably. variable substitution is also pretty badly designed and error prone. A $var:q operator helps to write more reliable code involving variables. Summary Stay away from csh if you can. If you can't use: single quotes to quote most characters. ! and newline still need a \ . \ can escape most characters "..." can allow some expansions within it, but that's pretty buggy if they embed newline and/or backslash characters, best may be to use single quotes only and $var:q for variable expansion. You'll need to use loops if you want to join elements of an array reliably. rc family rc is the plan9 shell. plan9 code has now been released as FLOSS and its user space software including rc been ported to Linux. A clone of rc for Unix was also written in the early 90s by Byron Rakitzis, and from which derived es and akanga . That's a shell with a much cleaner and better syntax and the one everyone would be using if we weren't stuck with Bourne-like shells for backward compatibility. rc / akanga Special characters #;&|^$=`'{}()<> , SPC, TAB and NEWLINE are always special when not quoted. *?[ are globbing operators. Quoting operator '...' is the only quoting operator. A litteral ' is written with '' within single quotes as in: echo 'it''s so simple isn''t it?' es es could be seen as an experimental shell based on rc . It has a few differences though. The one of interest for this Q/A is that \ is also a quoting operator (that quotes all special characters except newline) and can also be used to introduce escape sequences like \n for newline, \b for backslash... fish fish is a relative newcomer (circa 2005), is primarily intended for interactive use and also has a significantly different syntax from other shells. special characters "'\()$%{}^<>;&| always special when not quoted (note the % (for pid expansion) as a significant difference from other shells, and ` is not special) # (comment) special when following unquoted space, tab, newline or ;&|^<> *? (but not [...] ) globbing operators Quoting operators \ quotes a single special character except newline, but beware it also doubles as a C escape sequence ( \n , \b ...) introducer. IOW, \n is not a quoted n but a newline. "..." quotes everything but itself, $ and backslash and backslash can be used to escape those. \<newline> is a line continuation (removed) inside "..." . '...' quotes everything but itself and \ , and you can use backslash to escape those.
{ "score": 6, "source": [ "https://unix.stackexchange.com/questions/296141", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/81848/" ] }