2020年02月25日 に更新

bashの特異な書き方集

Sign inTop StoryMedium TipsSubmitCreate a Simple Ruby GemFerris BoranFollowJun 20, 2019 · 3 min readIt’s a rubyMake the Basic FoldersEvery gem needs at least a root folder and a lib folder. In terminal, enter the following:$ mkdir my_gem$ cd my_gem$ mkdir libOr copy and paste: mkdir my_gem && cd my_gem && mkdir libCreate the First Gem CodeMake the name of the file the same name as the gem. This file is solely responsible for setting up your gem. You can still break up your code into different files but make sure your main gem file has access to it by adding require '<path to file>' .$ cd lib$ > my_gem.rbOr copy and paste: cd lib && > my_gem.rb> is just a shortcut for touchAdd Some Function# ./lib/my_gem.rbmodule MyGem class Here def self.here? puts "Ferris was here" end endendYou don’t have to put it in a module:# ./lib/my_gem.rbclass MyGem def self.here? puts "Ferris was here" endendCreate the gemspec File in the Root Directory$ > my_gem.gemspecThe gemspec file holds the information about the gem.There are 5 required fields:name — The name of your gemversion — The current version of your gemsummary — A summary of what your gem doesauthors — Who wrote the gemfiles — The files needed to make your gem function (Your gem will still build without files listed but it won’t work)There are 2 fields that will populate a warning if they are not present:homepage — Website for your gemlicense — Lets users know what and how they are allowed to use your gemA couple of recommended fields:description — A description of your gememail — Your contact email# ./my_gem.gemspecGem::Specification.new do |s| ### REQUIRED ### s.name = 'my_gem' s.version = '0.0.0' s.summary = "This is My_Gem" s.authors = ["Ferris Boran"] s.files = ["lib/my_gem.rb"] ### WARNING ### s.homepage = 'https://mygem.com' s.license = 'OML' ### RECOMMENDED ### s.description = "A simple test gem" # nice to have s.email = 'ferris@email.com # nice to haveendBuild and Install$ gem build my_gemIf all goes well you should see something like this in your terminal$ Successfully built RubyGem Name: my_gem Version: 0.0.0 File: my_gem-0.0.0.gem$ gem install my_gem-0.0.0.gemSame as before, you should get back something like this$ Successfully installed my_gem-0.0.0 Parsing documentation for my_gem-0.0.0 Done installing documentation for test after 0 seconds 1 gem installedRequire Your Gem and Use ItAdd it to your Gemfile# <your app>/Gemfilegem 'my_gem'Require it require 'my_gem' wherever you need it### If using a module ###require 'my_gem'class WhoWasHere < MyGem::Here self.here?end### If using a class ###require 'my_gem'MyGem.here?Now when you run your app your gem will do what you designed it to do!Module ExampleClass ExampleSourcesRubyGems — https://guides.rubygems.org/Ruby Gem Licenses — https://spdx.org/licenses/The StartupMedium's largest active publication, followed by +586K people. Follow to join our community.Follow206 RubyRubygemsProgrammingCodingRails206 clapsWritten byFerris BoranFollowFull-Stack Developer and Automation EngineerFollowThe StartupFollowMedium's largest active publication, followed by +586K people. Follow to join our community.FollowWrite the first responseDiscover MediumWelcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. WatchMake Medium yoursFollow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. ExploreBecome a memberGet unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. UpgradeAboutHelpLegal
By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up. Sign up to join this community Anybody can ask a question Anybody can answer The best answers are voted up and rise to the top What does <<< mean? [duplicate] Ask Question Asked 6 years, 8 months ago Active 3 months ago Viewed 116k times 133 65 This question already has answers here: Command line: <<< instead of << (2 answers) Closed 6 years ago. What does <<< mean? Here is an example: $ sed 's/a/b/g' <<< "aaa" bbb Is it something general that works with more Linux commands? It looks like it's feeding the sed program with the string aaa, but isn't << or < usually used for that? bash command-line sed command share|improve this question asked Jun 22 '13 at 16:36 Daniel JonssonDaniel Jonsson 1,43522 gold badges99 silver badges88 bronze badges 1 it seems < is for passing file (or directory), << @ for passing multiple lines (similar to the banner command in cisco switches; as terminated by a custom string @ in this case), and <<< to pass a string (instead of file). test them yourself with cat and you'll grasp it very quickly. – user86041 Oct 5 '17 at 10:32 add a comment  |  4 Answers 4 active oldest votes 178 Others have answered the basic question: what is it? Let's look at why it's useful. You can also feed a string to a command's stdin like this: echo "$string" | command However in bash, introducing a pipe means the individual commands are run in subshells. Consider this: echo "hello world" | read first second echo $second $first The output of the 2nd echo command prints just a single space. Whaaaa? What happened to my variables? Because the read command is in a pipeline, it is run in a subshell. It correctly reads 2 words from its stdin and assigns to the variables. But then the command completes, the subshell exits and the variables are lost. Sometimes you can work around this with braces: echo "hello world" | { read first second echo $second $first } That's OK if your need for the values is contained, but you still don't have those variables in the current shell of your script. To remedy this confusing situation, use a here-string read first second <<< "hello world" echo $second $first Ah, much better! share|improve this answer edited Nov 9 '19 at 22:22 answered Jun 22 '13 at 18:31 glenn jackmanglenn jackman 59.9k88 gold badges8484 silver badges126126 bronze badges 10 In addition to here-strings, process substutitions are very useful for the same reasons. – glenn jackman Jun 22 '13 at 18:32 4 This is a fantastic explanation of <<< as well as pipes and sub-shells! I learned both from this. – David Mann May 12 '17 at 1:29 1 One note, with the simple echo ...|read example, the pipeline can work to set the variables in the current shell if you (1) enable the "lastpipe" shell option (shopt -s lastpipe) and (2) disable job control (set +m) – glenn jackman Aug 9 '17 at 20:00 1 First the here string is a single string so if it contains whitespace you need quotes. Second the read command doesn't output anything so you'll have to clarify "nothing" – glenn jackman May 23 '18 at 21:43 2 Very interesting. The case you give does not result in unexpected behavior using zsh. – Ryan Ward May 8 '19 at 21:00  |  show 4 more comments 83 <<< denotes a here string. $ cat <<< 'hi there' hi there It passes the word on the right to the standard input of the command on the left. << denotes a here document. $ cat <<EOF > hi > there > EOF hi there EOF can be any word. Here documents are commonly used in shell scripts to create whole files or to display long messages. cat > some-file <<FILE foo bar bar bar foo foo FILE < passes the contents of a file to a command's standard input. $ cat < /etc/fstab /dev/sda2 /boot ext4 nosuid,noexec,nodev,rw,noatime,nodiratime 0 2 /dev/sda4 / ext4 rw,noatime,nodiratime, 0 1 /dev/sdb5 /var ext4 nosuid,noexec,nodev,rw,relatime 0 2 ... share|improve this answer edited Oct 5 '17 at 10:23 RomanPerekhrest 25.5k11 gold badge3333 silver badges5555 bronze badges answered Jun 22 '13 at 17:40 user26112user26112 5 Is there a reason why someone would want cat < /etc/fstab instead of just cat /etc/fstab? Or is cat just a suboptimal example here? – Griddo Jul 31 '18 at 7:06 In the first case, cat opens the file, and in the second case, the shell opens the file, passing it as cat's standard input. quote from unix.stackexchange.com/questions/258931/… – star Apr 19 '19 at 0:53 4 I can't think of a reason why cat < file would ever be better than cat file. However, there are some cases where there is a difference -- for example, grep string file is different from grep string < file in that the second form doesn't prefix "file:" in front of every line. "cat file | grep string" is better written as "grep string < file". Not that any of this is worth doing for performance alone these days, but it is better coding practice. – Brian C Jul 9 '19 at 3:43 add a comment  |  16 Take a look at the Bash man page. This notation is part of what's called a here documents & here strings. It allows you the ability to generate multi-line data input as one continuous string. The variation you're asking about is called a here string. excerpt from Bash man page Here Strings A variant of here documents, the format is: <<<word The word is expanded and supplied to the command on its standard input. share|improve this answer answered Jun 22 '13 at 17:18 slm♦slm 290k8383 gold badges612612 silver badges751751 bronze badges add a comment  |  5 It means here strings. <<< strings The strings is expanded and supplied to the command on its standard input. In your example, strings aaa is feed to sed command via stdin. share|improve this answer answered Jun 22 '13 at 16:42 cuonglmcuonglm 118k2828 gold badges241241 silver badges339339 bronze badges add a comment  |  Not the answer you're looking for? Browse other questions tagged bash command-line sed command or ask your own question. Blog Ben Popper is the Worst Coder : Complexity is the Constant How to onboard yourself when your employer doesn’t Featured on Meta The company’s commitment to rebuilding the relationship with you, our community Linked 71 Command line: <<< instead of << 70 Difference between “cat” and “cat <” 3 How to convert a String into Array in shell script 0 Extract filename and substitute 1 How to wrap a string around large gzip file? -2 bash + how to capture the first/seconf/thired field Related 0What is the concept hidden behind the term “command”?0Regex for matchng anything between parenthesis1Feeding audio from microphone live into python2What does :: do in script of sed5Count the number of occurrences of a substring in a string0What does “`_`, `-`, `--` or the empty string is used for the shell's error messages” mean?1What does these two commands Hot Network Questions Can frequent light bicycle communting severely damage pants? Tips for being the first graduate student of a PI? Are photons aged? What is the bleu score of professional human translators? What set is this piece used for Are students required to attend Quidditch matches? One reviewer in the committee rejected my Ph.D. defense but he didn't attend Other than the electric guitar, which plucked chordophones (guitar-like instruments) originated in the United States? With all six, I’m set free Does Nyxbloom Ancient replace the entire mana ability or just the part that produces mana? I lost my boarding pass with my bag tag on it, does this matter? Did Sir Arthur Conan Doyle prank 12 men into fleeing their countries? Can "more" be used without "than"? How add lemon flavor to scallops with fresh lemons? How does Flixbus get between London to mainland Europe? How do I fix this drill hole on countertop? Why do most languages have a different form for singular vs plural nouns? Is possible to define a bash script to run interactively by default? Is Hillary Clinton a super delegate in 2020? Does "lebensspendend" (with double s) officially exist? What does this dot and bemol mean? Getting an ordered list of id's of selected objects using PyQGIS Why were the drawings of Colossus burnt after WW2 and why was its very existence "of course" kept secret? Does anybody know what this symbol means on my Samsung travel adapter? more hot questions lang-bsh Unix & Linux Stack Exchange works best with JavaScript enabled
You can iterate the sequence of numbers in bash by two ways. One is by using seq command and another is by specifying range in for loop. In seq command, the sequence starts from one, the number increments by one in each step and print each number in each line up to the upper limit by default. If the number starts from upper limit then it decrements by one in each step. Normally, all numbers are interpreted as floating point but if the sequence starts from integer then the list of decimal integers will print. If seq command can execute successfully then it returns 0, otherwise it returns any non-zero number. You can also iterate the sequence of numbers using for loop with range. Both seq command and for loop with range are shown in this tutorial by using examples. The options of seq command: You can use seq command by using the following options. -w This option is used to pad the numbers with leading zeros to print all numbers with equal width. -f format This option is used to print number with particular format. Floating number can be formatted by using %f, %g and %e as conversion characters. %g is used as default. -s string This option is used to separate the numbers with string. The default value is newline (‘\n’). Examples of seq command: You can apply seq command by three ways. You can use only upper limit or upper and lower limit or upper and lower limit with increment or decrement value of each step . Different uses of the seq command with options are shown in the following examples. Example-1: seq command without option When only upper limit is used then the number will start from 1 and increment by one in each step. The following command will print the number from 1 to 4. $ seq 4 Output: When the two values are used with seq command then first value will be used as starting number and second value will be used as ending number. The following command will print the number from 7 to 15. $ seq 7 15 Output: When you will use three values with seq command then the second value will be used as increment or decrement value for each step. For the following command, the starting number is 10, ending number is 1 and each step will be counted by decrementing 2. $ seq 10 -2 1 Output: Example-2: seq with –w option The following command will print the output by adding leading zero for the number from 1 to 9. $ seq -w 0110 Output: Example-3: seq with –s option The following command uses “-“ as separator for each sequence number. The sequence of numbers will print by adding “-“ as separator. $ seq -s - 8 Output: Example-4: seq with -f option The following command will print 10 date values starting from 1. Here, “%g” option is used to add sequence number with other string value. $ seq -f "%g/04/2018" 10 output: The following command is used to generate the sequence of floating point number using “%f” . Here, the number will start from 3 and increment by 0.8 in each step and the last number will be less than or equal to 6. $ seq -f "%f" 3 0.8 6 Output: Example-5: Write the sequence in a file If you want to save the sequence of number into a file without printing in the console then you can use the following commands. The first command will print the numbers to a file named “seq.txt”. The number will generate from 5 to 20 and increment by 10 in each step. The second command is used to view the content of “seq.txt” file. $ seq 5 10 20 | cat &gt; seq.txt $ cat seq.txt Output: Example-6: Using seq in for loop Suppose, you want to create files named fn1 to fn10 using for loop with seq. Create a file named “sq1.bash” and add the following code. For loop will iterate for 10 times using seq command and create 10 files in the sequence fn1, fn2,fn3…..fn10. #!/bin/bash for i in `seq 10` do touch fn.$i done Output: Run the following commands to execute the code of the bash file and check the files are created or not. $ bash sq1.bash $ ls Examples of for loop with range: Example-7: For loop with range The alternative of seq command is range. You can use range in for loop to generate sequence of numbers like seq. Write the following code in a bash file named “sq2.bash”. The loop will iterate for 5 times and print the square root of each number in each step. #!/bin/bash for n in {1..5} do ((result=n*n)) echo $n square=$result done Output: Run the command to execute the script of the file. $ bash sq2.bash Example-8: For loop with range and increment value By default, the number is increment by one in each step in range like seq. You can also change the increment value in range. Write the following code in a bash file named “sq3.bash”.  The for loop in the script will iterate for 5 times, each step is incremented by 2 and print all odd numbers between 1 to 10. #!/bin/bash echo "all odd numbers from 1 to 10 are" for i in {1..10..2} do echo $i; done Output: Run the command to execute the script of the file. $ bash sq3.bash If you want to work with the sequence of numbers then you can use any of the options that are shown in this tutorial. After completing this tutorial, you will be able to use seq command and for loop with range more efficiently in your bash script. About the author Fahmida Yesmin I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help. View all posts